src/HOL/Tools/Datatype/datatype_rep_proofs.ML
author wenzelm
Thu Oct 29 23:49:55 2009 +0100 (2009-10-29)
changeset 33338 de76079f973a
parent 33278 ba9f52f56356
child 33643 b275f26a638b
permissions -rw-r--r--
eliminated some old folds;
berghofe@5177
     1
(*  Title:      HOL/Tools/datatype_rep_proofs.ML
wenzelm@11539
     2
    Author:     Stefan Berghofer, TU Muenchen
berghofe@5177
     3
berghofe@5177
     4
Definitional introduction of datatypes
berghofe@5177
     5
Proof of characteristic theorems:
berghofe@5177
     6
berghofe@5177
     7
 - injectivity of constructors
berghofe@7228
     8
 - distinctness of constructors
berghofe@5177
     9
 - induction theorem
berghofe@5177
    10
*)
berghofe@5177
    11
berghofe@5177
    12
signature DATATYPE_REP_PROOFS =
berghofe@5177
    13
sig
haftmann@31737
    14
  include DATATYPE_COMMON
haftmann@31737
    15
  val representation_proofs : config -> info Symtab.table ->
haftmann@31668
    16
    string list -> descr list -> (string * sort) list ->
wenzelm@30345
    17
      (binding * mixfix) list -> (binding * mixfix) list list -> attribute
haftmann@32907
    18
        -> theory -> (thm list list * thm list list * thm) * theory
berghofe@5177
    19
end;
berghofe@5177
    20
berghofe@5177
    21
structure DatatypeRepProofs : DATATYPE_REP_PROOFS =
berghofe@5177
    22
struct
berghofe@5177
    23
berghofe@5177
    24
open DatatypeAux;
berghofe@5177
    25
berghofe@5177
    26
val (_ $ (_ $ (_ $ (distinct_f $ _) $ _))) = hd (prems_of distinct_lemma);
berghofe@5177
    27
berghofe@21021
    28
val collect_simp = rewrite_rule [mk_meta_eq mem_Collect_eq];
berghofe@21021
    29
wenzelm@11435
    30
wenzelm@11435
    31
(** theory context references **)
berghofe@5177
    32
haftmann@31737
    33
fun exh_thm_of (dt_info : info Symtab.table) tname =
haftmann@32712
    34
  #exhaust (the (Symtab.lookup dt_info tname));
berghofe@5177
    35
berghofe@5177
    36
(******************************************************************************)
berghofe@5177
    37
haftmann@31737
    38
fun representation_proofs (config : config) (dt_info : info Symtab.table)
wenzelm@8436
    39
      new_type_names descr sorts types_syntax constr_syntax case_names_induct thy =
berghofe@5177
    40
  let
wenzelm@19540
    41
    val Datatype_thy = ThyInfo.the_theory "Datatype" thy;
wenzelm@20820
    42
    val node_name = "Datatype.node";
wenzelm@20820
    43
    val In0_name = "Datatype.In0";
wenzelm@20820
    44
    val In1_name = "Datatype.In1";
wenzelm@20820
    45
    val Scons_name = "Datatype.Scons";
wenzelm@20820
    46
    val Leaf_name = "Datatype.Leaf";
wenzelm@20820
    47
    val Numb_name = "Datatype.Numb";
wenzelm@20820
    48
    val Lim_name = "Datatype.Lim";
berghofe@13641
    49
    val Suml_name = "Datatype.Suml";
berghofe@13641
    50
    val Sumr_name = "Datatype.Sumr";
berghofe@7015
    51
berghofe@13641
    52
    val [In0_inject, In1_inject, Scons_inject, Leaf_inject,
berghofe@13641
    53
         In0_eq, In1_eq, In0_not_In1, In1_not_In0,
wenzelm@26343
    54
         Lim_inject, Suml_inject, Sumr_inject] = map (PureThy.get_thm Datatype_thy)
wenzelm@26343
    55
          ["In0_inject", "In1_inject", "Scons_inject", "Leaf_inject",
wenzelm@26343
    56
           "In0_eq", "In1_eq", "In0_not_In1", "In1_not_In0",
wenzelm@26343
    57
           "Lim_inject", "Suml_inject", "Sumr_inject"];
berghofe@5177
    58
wenzelm@28362
    59
    val descr' = flat descr;
berghofe@5177
    60
berghofe@5661
    61
    val big_name = space_implode "_" new_type_names;
haftmann@32124
    62
    val thy1 = Sign.add_path big_name thy;
berghofe@5661
    63
    val big_rec_name = big_name ^ "_rep_set";
berghofe@21021
    64
    val rep_set_names' =
berghofe@5177
    65
      (if length descr' = 1 then [big_rec_name] else
berghofe@5177
    66
        (map ((curry (op ^) (big_rec_name ^ "_")) o string_of_int)
berghofe@5177
    67
          (1 upto (length descr'))));
haftmann@28965
    68
    val rep_set_names = map (Sign.full_bname thy1) rep_set_names';
berghofe@5177
    69
berghofe@5661
    70
    val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
berghofe@5661
    71
    val leafTs' = get_nonrec_types descr' sorts;
berghofe@7015
    72
    val branchTs = get_branching_types descr' sorts;
berghofe@7015
    73
    val branchT = if null branchTs then HOLogic.unitT
wenzelm@32765
    74
      else Balanced_Tree.make (fn (T, U) => Type ("+", [T, U])) branchTs;
haftmann@33040
    75
    val arities = remove (op =) 0 (get_arities descr');
wenzelm@33338
    76
    val unneeded_vars =
wenzelm@33338
    77
      subtract (op =) (List.foldr OldTerm.add_typ_tfree_names [] (leafTs' @ branchTs)) (hd tyvars);
wenzelm@33338
    78
    val leafTs = leafTs' @ map (fn n => TFree (n, (the o AList.lookup (op =) sorts) n)) unneeded_vars;
berghofe@5177
    79
    val recTs = get_rec_types descr' sorts;
skalberg@15570
    80
    val newTs = Library.take (length (hd descr), recTs);
skalberg@15570
    81
    val oldTs = Library.drop (length (hd descr), recTs);
berghofe@5177
    82
    val sumT = if null leafTs then HOLogic.unitT
wenzelm@32765
    83
      else Balanced_Tree.make (fn (T, U) => Type ("+", [T, U])) leafTs;
berghofe@7015
    84
    val Univ_elT = HOLogic.mk_setT (Type (node_name, [sumT, branchT]));
berghofe@5177
    85
    val UnivT = HOLogic.mk_setT Univ_elT;
berghofe@21021
    86
    val UnivT' = Univ_elT --> HOLogic.boolT;
berghofe@21021
    87
    val Collect = Const ("Collect", UnivT' --> UnivT);
berghofe@5177
    88
berghofe@5177
    89
    val In0 = Const (In0_name, Univ_elT --> Univ_elT);
berghofe@5177
    90
    val In1 = Const (In1_name, Univ_elT --> Univ_elT);
berghofe@5177
    91
    val Leaf = Const (Leaf_name, sumT --> Univ_elT);
berghofe@7015
    92
    val Lim = Const (Lim_name, (branchT --> Univ_elT) --> Univ_elT);
berghofe@5177
    93
berghofe@5177
    94
    (* make injections needed for embedding types in leaves *)
berghofe@5177
    95
berghofe@5177
    96
    fun mk_inj T' x =
berghofe@5177
    97
      let
berghofe@5177
    98
        fun mk_inj' T n i =
berghofe@5177
    99
          if n = 1 then x else
berghofe@5177
   100
          let val n2 = n div 2;
berghofe@5177
   101
              val Type (_, [T1, T2]) = T
berghofe@5177
   102
          in
berghofe@5177
   103
            if i <= n2 then
paulson@15391
   104
              Const ("Sum_Type.Inl", T1 --> T) $ (mk_inj' T1 n2 i)
berghofe@5177
   105
            else
paulson@15391
   106
              Const ("Sum_Type.Inr", T2 --> T) $ (mk_inj' T2 (n - n2) (i - n2))
berghofe@5177
   107
          end
haftmann@31986
   108
      in mk_inj' sumT (length leafTs) (1 + find_index (fn T'' => T'' = T') leafTs)
berghofe@5177
   109
      end;
berghofe@5177
   110
berghofe@5177
   111
    (* make injections for constructors *)
berghofe@5177
   112
wenzelm@32765
   113
    fun mk_univ_inj ts = Balanced_Tree.access
wenzelm@23419
   114
      {left = fn t => In0 $ t,
wenzelm@23419
   115
        right = fn t => In1 $ t,
wenzelm@23419
   116
        init =
haftmann@28524
   117
          if ts = [] then Const (@{const_name undefined}, Univ_elT)
wenzelm@23419
   118
          else foldr1 (HOLogic.mk_binop Scons_name) ts};
berghofe@5177
   119
berghofe@7015
   120
    (* function spaces *)
berghofe@7015
   121
berghofe@7015
   122
    fun mk_fun_inj T' x =
berghofe@7015
   123
      let
berghofe@7015
   124
        fun mk_inj T n i =
berghofe@7015
   125
          if n = 1 then x else
berghofe@7015
   126
          let
berghofe@7015
   127
            val n2 = n div 2;
berghofe@7015
   128
            val Type (_, [T1, T2]) = T;
berghofe@13641
   129
            fun mkT U = (U --> Univ_elT) --> T --> Univ_elT
berghofe@7015
   130
          in
berghofe@13641
   131
            if i <= n2 then Const (Suml_name, mkT T1) $ mk_inj T1 n2 i
berghofe@13641
   132
            else Const (Sumr_name, mkT T2) $ mk_inj T2 (n - n2) (i - n2)
berghofe@7015
   133
          end
haftmann@31986
   134
      in mk_inj branchT (length branchTs) (1 + find_index (fn T'' => T'' = T') branchTs)
berghofe@7015
   135
      end;
berghofe@7015
   136
wenzelm@33338
   137
    fun mk_lim t Ts = fold_rev (fn T => fn t => Lim $ mk_fun_inj T (Abs ("x", T, t))) Ts t;
berghofe@13641
   138
berghofe@5177
   139
    (************** generate introduction rules for representing set **********)
berghofe@5177
   140
haftmann@31668
   141
    val _ = message config "Constructing representing sets ...";
berghofe@5177
   142
berghofe@5177
   143
    (* make introduction rule for a single constructor *)
berghofe@5177
   144
berghofe@5177
   145
    fun make_intr s n (i, (_, cargs)) =
berghofe@5177
   146
      let
wenzelm@33338
   147
        fun mk_prem dt (j, prems, ts) =
wenzelm@33338
   148
          (case strip_dtyp dt of
berghofe@13641
   149
            (dts, DtRec k) =>
berghofe@13641
   150
              let
berghofe@13641
   151
                val Ts = map (typ_of_dtyp descr' sorts) dts;
berghofe@13641
   152
                val free_t =
berghofe@13641
   153
                  app_bnds (mk_Free "x" (Ts ---> Univ_elT) j) (length Ts)
berghofe@13641
   154
              in (j + 1, list_all (map (pair "x") Ts,
berghofe@21021
   155
                  HOLogic.mk_Trueprop
haftmann@31949
   156
                    (Free (nth rep_set_names' k, UnivT') $ free_t)) :: prems,
skalberg@15574
   157
                mk_lim free_t Ts :: ts)
berghofe@5177
   158
              end
berghofe@13641
   159
          | _ =>
berghofe@5177
   160
              let val T = typ_of_dtyp descr' sorts dt
berghofe@5177
   161
              in (j + 1, prems, (Leaf $ mk_inj T (mk_Free "x" T j))::ts)
berghofe@13641
   162
              end);
berghofe@5177
   163
wenzelm@33338
   164
        val (_, prems, ts) = fold_rev mk_prem cargs (1, [], []);
berghofe@21021
   165
        val concl = HOLogic.mk_Trueprop
berghofe@21021
   166
          (Free (s, UnivT') $ mk_univ_inj ts n i)
berghofe@13641
   167
      in Logic.list_implies (prems, concl)
berghofe@5177
   168
      end;
berghofe@5177
   169
wenzelm@28362
   170
    val intr_ts = maps (fn ((_, (_, _, constrs)), rep_set_name) =>
berghofe@5177
   171
      map (make_intr rep_set_name (length constrs))
wenzelm@28362
   172
        ((1 upto (length constrs)) ~~ constrs)) (descr' ~~ rep_set_names');
berghofe@5177
   173
wenzelm@21365
   174
    val ({raw_induct = rep_induct, intrs = rep_intrs, ...}, thy2) =
wenzelm@33278
   175
      thy1
wenzelm@33278
   176
      |> Sign.map_naming Name_Space.conceal
wenzelm@33278
   177
      |> Inductive.add_inductive_global (serial ())
haftmann@31668
   178
          {quiet_mode = #quiet config, verbose = false, kind = Thm.internalK,
haftmann@28965
   179
           alt_name = Binding.name big_rec_name, coind = false, no_elim = true, no_ind = false,
wenzelm@29389
   180
           skip_mono = true, fork_mono = false}
haftmann@28965
   181
          (map (fn s => ((Binding.name s, UnivT'), NoSyn)) rep_set_names') []
wenzelm@33278
   182
          (map (fn x => (Attrib.empty_binding, x)) intr_ts) []
wenzelm@33278
   183
      ||> Sign.restore_naming thy1
wenzelm@33278
   184
      ||> Theory.checkpoint;
berghofe@5177
   185
berghofe@5177
   186
    (********************************* typedef ********************************)
berghofe@5177
   187
berghofe@21021
   188
    val (typedefs, thy3) = thy2 |>
haftmann@32124
   189
      Sign.parent_path |>
berghofe@21021
   190
      fold_map (fn ((((name, mx), tvs), c), name') =>
haftmann@31723
   191
          Typedef.add_typedef false (SOME (Binding.name name')) (name, tvs, mx)
berghofe@21021
   192
            (Collect $ Const (c, UnivT')) NONE
berghofe@21021
   193
            (rtac exI 1 THEN rtac CollectI 1 THEN
berghofe@21021
   194
              QUIET_BREADTH_FIRST (has_fewer_prems 1)
wenzelm@26475
   195
              (resolve_tac rep_intrs 1)))
berghofe@21021
   196
                (types_syntax ~~ tyvars ~~
berghofe@21021
   197
                  (Library.take (length newTs, rep_set_names)) ~~ new_type_names) ||>
haftmann@32124
   198
      Sign.add_path big_name;
berghofe@5177
   199
berghofe@5177
   200
    (*********************** definition of constructors ***********************)
berghofe@5177
   201
berghofe@5177
   202
    val big_rep_name = (space_implode "_" new_type_names) ^ "_Rep_";
berghofe@5177
   203
    val rep_names = map (curry op ^ "Rep_") new_type_names;
berghofe@5177
   204
    val rep_names' = map (fn i => big_rep_name ^ (string_of_int i))
wenzelm@28362
   205
      (1 upto (length (flat (tl descr))));
wenzelm@22578
   206
    val all_rep_names = map (Sign.intern_const thy3) rep_names @
haftmann@28965
   207
      map (Sign.full_bname thy3) rep_names';
berghofe@5177
   208
berghofe@5177
   209
    (* isomorphism declarations *)
berghofe@5177
   210
wenzelm@30345
   211
    val iso_decls = map (fn (T, s) => (Binding.name s, T --> Univ_elT, NoSyn))
berghofe@5177
   212
      (oldTs ~~ rep_names');
berghofe@5177
   213
berghofe@5177
   214
    (* constructor definitions *)
berghofe@5177
   215
wenzelm@33244
   216
    fun make_constr_def tname T n ((cname, cargs), (cname', mx)) (thy, defs, eqns, i) =
berghofe@5177
   217
      let
wenzelm@33338
   218
        fun constr_arg dt (j, l_args, r_args) =
berghofe@5177
   219
          let val T = typ_of_dtyp descr' sorts dt;
berghofe@5177
   220
              val free_t = mk_Free "x" T j
berghofe@13641
   221
          in (case (strip_dtyp dt, strip_type T) of
skalberg@15574
   222
              ((_, DtRec m), (Us, U)) => (j + 1, free_t :: l_args, mk_lim
haftmann@31949
   223
                (Const (nth all_rep_names m, U --> Univ_elT) $
skalberg@15574
   224
                   app_bnds free_t (length Us)) Us :: r_args)
berghofe@5177
   225
            | _ => (j + 1, free_t::l_args, (Leaf $ mk_inj T free_t)::r_args))
berghofe@5177
   226
          end;
berghofe@5177
   227
wenzelm@33338
   228
        val (_, l_args, r_args) = fold_rev constr_arg cargs (1, [], []);
berghofe@5177
   229
        val constrT = (map (typ_of_dtyp descr' sorts) cargs) ---> T;
wenzelm@22578
   230
        val abs_name = Sign.intern_const thy ("Abs_" ^ tname);
wenzelm@22578
   231
        val rep_name = Sign.intern_const thy ("Rep_" ^ tname);
berghofe@5177
   232
        val lhs = list_comb (Const (cname, constrT), l_args);
berghofe@5177
   233
        val rhs = mk_univ_inj r_args n i;
wenzelm@27330
   234
        val def = Logic.mk_equals (lhs, Const (abs_name, Univ_elT --> T) $ rhs);
wenzelm@30364
   235
        val def_name = Long_Name.base_name cname ^ "_def";
berghofe@5177
   236
        val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
berghofe@5177
   237
          (Const (rep_name, T --> Univ_elT) $ lhs, rhs));
haftmann@18377
   238
        val ([def_thm], thy') =
haftmann@18377
   239
          thy
wenzelm@24712
   240
          |> Sign.add_consts_i [(cname', constrT, mx)]
haftmann@29579
   241
          |> (PureThy.add_defs false o map Thm.no_attributes) [(Binding.name def_name, def)];
berghofe@5177
   242
wenzelm@8436
   243
      in (thy', defs @ [def_thm], eqns @ [eqn], i + 1) end;
berghofe@5177
   244
berghofe@5177
   245
    (* constructor definitions for datatype *)
berghofe@5177
   246
wenzelm@33244
   247
    fun dt_constr_defs ((((_, (_, _, constrs)), tname), T), constr_syntax)
wenzelm@33244
   248
        (thy, defs, eqns, rep_congs, dist_lemmas) =
berghofe@5177
   249
      let
berghofe@5177
   250
        val _ $ (_ $ (cong_f $ _) $ _) = concl_of arg_cong;
wenzelm@22578
   251
        val rep_const = cterm_of thy
wenzelm@22578
   252
          (Const (Sign.intern_const thy ("Rep_" ^ tname), T --> Univ_elT));
wenzelm@32957
   253
        val cong' =
wenzelm@32957
   254
          Drule.standard (cterm_instantiate [(cterm_of thy cong_f, rep_const)] arg_cong);
wenzelm@32957
   255
        val dist =
wenzelm@32957
   256
          Drule.standard (cterm_instantiate [(cterm_of thy distinct_f, rep_const)] distinct_lemma);
wenzelm@33244
   257
        val (thy', defs', eqns', _) = fold ((make_constr_def tname T) (length constrs))
wenzelm@33244
   258
          (constrs ~~ constr_syntax) (Sign.add_path tname thy, defs, [], 1);
berghofe@5177
   259
      in
haftmann@32124
   260
        (Sign.parent_path thy', defs', eqns @ [eqns'],
berghofe@5177
   261
          rep_congs @ [cong'], dist_lemmas @ [dist])
berghofe@5177
   262
      end;
berghofe@5177
   263
wenzelm@33244
   264
    val (thy4, constr_defs, constr_rep_eqns, rep_congs, dist_lemmas) =
wenzelm@33244
   265
      fold dt_constr_defs
wenzelm@33244
   266
        (hd descr ~~ new_type_names ~~ newTs ~~ constr_syntax)
wenzelm@33244
   267
        (thy3 |> Sign.add_consts_i iso_decls |> Sign.parent_path, [], [], [], []);
wenzelm@33244
   268
berghofe@5177
   269
berghofe@5177
   270
    (*********** isomorphisms for new types (introduced by typedef) ***********)
berghofe@5177
   271
haftmann@31668
   272
    val _ = message config "Proving isomorphism properties ...";
berghofe@5177
   273
berghofe@21021
   274
    val newT_iso_axms = map (fn (_, td) =>
berghofe@21021
   275
      (collect_simp (#Abs_inverse td), #Rep_inverse td,
berghofe@21021
   276
       collect_simp (#Rep td))) typedefs;
berghofe@5177
   277
berghofe@21021
   278
    val newT_iso_inj_thms = map (fn (_, td) =>
berghofe@21021
   279
      (collect_simp (#Abs_inject td) RS iffD1, #Rep_inject td RS iffD1)) typedefs;
berghofe@5177
   280
berghofe@5177
   281
    (********* isomorphisms between existing types and "unfolded" types *******)
berghofe@5177
   282
berghofe@5177
   283
    (*---------------------------------------------------------------------*)
berghofe@5177
   284
    (* isomorphisms are defined using primrec-combinators:                 *)
berghofe@5177
   285
    (* generate appropriate functions for instantiating primrec-combinator *)
berghofe@5177
   286
    (*                                                                     *)
berghofe@13641
   287
    (*   e.g.  dt_Rep_i = list_rec ... (%h t y. In1 (Scons (Leaf h) y))    *)
berghofe@5177
   288
    (*                                                                     *)
berghofe@5177
   289
    (* also generate characteristic equations for isomorphisms             *)
berghofe@5177
   290
    (*                                                                     *)
berghofe@13641
   291
    (*   e.g.  dt_Rep_i (cons h t) = In1 (Scons (dt_Rep_j h) (dt_Rep_i t)) *)
berghofe@5177
   292
    (*---------------------------------------------------------------------*)
berghofe@5177
   293
wenzelm@33244
   294
    fun make_iso_def k ks n (cname, cargs) (fs, eqns, i) =
berghofe@5177
   295
      let
berghofe@5177
   296
        val argTs = map (typ_of_dtyp descr' sorts) cargs;
haftmann@31949
   297
        val T = nth recTs k;
haftmann@31949
   298
        val rep_name = nth all_rep_names k;
berghofe@5177
   299
        val rep_const = Const (rep_name, T --> Univ_elT);
berghofe@5177
   300
        val constr = Const (cname, argTs ---> T);
berghofe@5177
   301
wenzelm@33244
   302
        fun process_arg ks' dt (i2, i2', ts, Ts) =
berghofe@13641
   303
          let
berghofe@13641
   304
            val T' = typ_of_dtyp descr' sorts dt;
berghofe@13641
   305
            val (Us, U) = strip_type T'
berghofe@13641
   306
          in (case strip_dtyp dt of
berghofe@13641
   307
              (_, DtRec j) => if j mem ks' then
skalberg@15574
   308
                  (i2 + 1, i2' + 1, ts @ [mk_lim (app_bnds
skalberg@15574
   309
                     (mk_Free "y" (Us ---> Univ_elT) i2') (length Us)) Us],
berghofe@13641
   310
                   Ts @ [Us ---> Univ_elT])
berghofe@5177
   311
                else
skalberg@15574
   312
                  (i2 + 1, i2', ts @ [mk_lim
haftmann@31949
   313
                     (Const (nth all_rep_names j, U --> Univ_elT) $
skalberg@15574
   314
                        app_bnds (mk_Free "x" T' i2) (length Us)) Us], Ts)
berghofe@7015
   315
            | _ => (i2 + 1, i2', ts @ [Leaf $ mk_inj T' (mk_Free "x" T' i2)], Ts))
berghofe@5177
   316
          end;
berghofe@5177
   317
wenzelm@33244
   318
        val (i2, i2', ts, Ts) = fold (process_arg ks) cargs (1, 1, [], []);
berghofe@5177
   319
        val xs = map (uncurry (mk_Free "x")) (argTs ~~ (1 upto (i2 - 1)));
berghofe@7015
   320
        val ys = map (uncurry (mk_Free "y")) (Ts ~~ (1 upto (i2' - 1)));
berghofe@5177
   321
        val f = list_abs_free (map dest_Free (xs @ ys), mk_univ_inj ts n i);
berghofe@5177
   322
wenzelm@33244
   323
        val (_, _, ts', _) = fold (process_arg []) cargs (1, 1, [], []);
berghofe@5177
   324
        val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
berghofe@5177
   325
          (rep_const $ list_comb (constr, xs), mk_univ_inj ts' n i))
berghofe@5177
   326
berghofe@5177
   327
      in (fs @ [f], eqns @ [eqn], i + 1) end;
berghofe@5177
   328
berghofe@5177
   329
    (* define isomorphisms for all mutually recursive datatypes in list ds *)
berghofe@5177
   330
wenzelm@33244
   331
    fun make_iso_defs ds (thy, char_thms) =
berghofe@5177
   332
      let
berghofe@5177
   333
        val ks = map fst ds;
berghofe@5177
   334
        val (_, (tname, _, _)) = hd ds;
wenzelm@17412
   335
        val {rec_rewrites, rec_names, ...} = the (Symtab.lookup dt_info tname);
berghofe@5177
   336
wenzelm@33244
   337
        fun process_dt (k, (tname, _, constrs)) (fs, eqns, isos) =
berghofe@5177
   338
          let
wenzelm@33244
   339
            val (fs', eqns', _) =
wenzelm@33244
   340
              fold (make_iso_def k ks (length constrs)) constrs (fs, eqns, 1);
haftmann@31949
   341
            val iso = (nth recTs k, nth all_rep_names k)
berghofe@5177
   342
          in (fs', eqns', isos @ [iso]) end;
berghofe@5177
   343
        
wenzelm@33244
   344
        val (fs, eqns, isos) = fold process_dt ds ([], [], []);
berghofe@5177
   345
        val fTs = map fastype_of fs;
wenzelm@30364
   346
        val defs = map (fn (rec_name, (T, iso_name)) => (Binding.name (Long_Name.base_name iso_name ^ "_def"),
wenzelm@27330
   347
          Logic.mk_equals (Const (iso_name, T --> Univ_elT),
wenzelm@27330
   348
            list_comb (Const (rec_name, fTs @ [T] ---> Univ_elT), fs)))) (rec_names ~~ isos);
wenzelm@28362
   349
        val (def_thms, thy') =
wenzelm@28362
   350
          apsnd Theory.checkpoint ((PureThy.add_defs false o map Thm.no_attributes) defs thy);
berghofe@5177
   351
berghofe@5177
   352
        (* prove characteristic equations *)
berghofe@5177
   353
oheimb@5553
   354
        val rewrites = def_thms @ (map mk_meta_eq rec_rewrites);
wenzelm@32970
   355
        val char_thms' = map (fn eqn => Skip_Proof.prove_global thy' [] [] eqn
wenzelm@20046
   356
          (fn _ => EVERY [rewrite_goals_tac rewrites, rtac refl 1])) eqns;
berghofe@5177
   357
berghofe@5177
   358
      in (thy', char_thms' @ char_thms) end;
berghofe@5177
   359
wenzelm@33244
   360
    val (thy5, iso_char_thms) = apfst Theory.checkpoint (fold_rev make_iso_defs
wenzelm@33244
   361
        (tl descr) (Sign.add_path big_name thy4, []));
berghofe@5177
   362
berghofe@5177
   363
    (* prove isomorphism properties *)
berghofe@5177
   364
wenzelm@28362
   365
    fun mk_funs_inv thy thm =
berghofe@7015
   366
      let
wenzelm@26626
   367
        val prop = Thm.prop_of thm;
berghofe@21021
   368
        val _ $ (_ $ ((S as Const (_, Type (_, [U, _]))) $ _ )) $
wenzelm@16287
   369
          (_ $ (_ $ (r $ (a $ _)) $ _)) = Type.freeze prop;
wenzelm@29270
   370
        val used = OldTerm.add_term_tfree_names (a, []);
berghofe@13641
   371
berghofe@13641
   372
        fun mk_thm i =
berghofe@13641
   373
          let
berghofe@13641
   374
            val Ts = map (TFree o rpair HOLogic.typeS)
wenzelm@20071
   375
              (Name.variant_list used (replicate i "'t"));
berghofe@13641
   376
            val f = Free ("f", Ts ---> U)
wenzelm@32970
   377
          in Skip_Proof.prove_global thy [] [] (Logic.mk_implies
berghofe@13641
   378
            (HOLogic.mk_Trueprop (HOLogic.list_all
berghofe@21021
   379
               (map (pair "x") Ts, S $ app_bnds f i)),
berghofe@13641
   380
             HOLogic.mk_Trueprop (HOLogic.mk_eq (list_abs (map (pair "x") Ts,
wenzelm@17985
   381
               r $ (a $ app_bnds f i)), f))))
berghofe@26806
   382
            (fn _ => EVERY [REPEAT_DETERM_N i (rtac ext 1),
berghofe@26806
   383
               REPEAT (etac allE 1), rtac thm 1, atac 1])
berghofe@13641
   384
          end
berghofe@13641
   385
      in map (fn r => r RS subst) (thm :: map mk_thm arities) end;
berghofe@7015
   386
berghofe@5177
   387
    (* prove  inj dt_Rep_i  and  dt_Rep_i x : dt_rep_set_i *)
berghofe@5177
   388
berghofe@26806
   389
    val fun_congs = map (fn T => make_elim (Drule.instantiate'
berghofe@26806
   390
      [SOME (ctyp_of thy5 T)] [] fun_cong)) branchTs;
berghofe@26806
   391
wenzelm@33338
   392
    fun prove_iso_thms ds (inj_thms, elem_thms) =
berghofe@5177
   393
      let
berghofe@5177
   394
        val (_, (tname, _, _)) = hd ds;
haftmann@32727
   395
        val induct = (#induct o the o Symtab.lookup dt_info) tname;
berghofe@5177
   396
berghofe@5177
   397
        fun mk_ind_concl (i, _) =
berghofe@5177
   398
          let
haftmann@31949
   399
            val T = nth recTs i;
haftmann@31949
   400
            val Rep_t = Const (nth all_rep_names i, T --> Univ_elT);
haftmann@31949
   401
            val rep_set_name = nth rep_set_names i
berghofe@5177
   402
          in (HOLogic.all_const T $ Abs ("y", T, HOLogic.imp $
berghofe@5177
   403
                HOLogic.mk_eq (Rep_t $ mk_Free "x" T i, Rep_t $ Bound 0) $
berghofe@5177
   404
                  HOLogic.mk_eq (mk_Free "x" T i, Bound 0)),
berghofe@21021
   405
              Const (rep_set_name, UnivT') $ (Rep_t $ mk_Free "x" T i))
berghofe@5177
   406
          end;
berghofe@5177
   407
berghofe@5177
   408
        val (ind_concl1, ind_concl2) = ListPair.unzip (map mk_ind_concl ds);
berghofe@5177
   409
oheimb@5553
   410
        val rewrites = map mk_meta_eq iso_char_thms;
berghofe@21021
   411
        val inj_thms' = map snd newT_iso_inj_thms @
haftmann@26359
   412
          map (fn r => r RS @{thm injD}) inj_thms;
berghofe@5177
   413
wenzelm@32970
   414
        val inj_thm = Skip_Proof.prove_global thy5 [] []
wenzelm@17985
   415
          (HOLogic.mk_Trueprop (mk_conj ind_concl1)) (fn _ => EVERY
haftmann@32712
   416
            [(indtac induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
berghofe@5177
   417
             REPEAT (EVERY
berghofe@5177
   418
               [rtac allI 1, rtac impI 1,
berghofe@5177
   419
                exh_tac (exh_thm_of dt_info) 1,
berghofe@5177
   420
                REPEAT (EVERY
berghofe@5177
   421
                  [hyp_subst_tac 1,
berghofe@5177
   422
                   rewrite_goals_tac rewrites,
berghofe@5177
   423
                   REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
berghofe@5177
   424
                   (eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1)
berghofe@5177
   425
                   ORELSE (EVERY
berghofe@13641
   426
                     [REPEAT (eresolve_tac (Scons_inject ::
berghofe@13641
   427
                        map make_elim [Leaf_inject, Inl_inject, Inr_inject]) 1),
berghofe@13641
   428
                      REPEAT (cong_tac 1), rtac refl 1,
berghofe@13641
   429
                      REPEAT (atac 1 ORELSE (EVERY
berghofe@13641
   430
                        [REPEAT (rtac ext 1),
berghofe@13641
   431
                         REPEAT (eresolve_tac (mp :: allE ::
berghofe@13641
   432
                           map make_elim (Suml_inject :: Sumr_inject ::
berghofe@26806
   433
                             Lim_inject :: inj_thms') @ fun_congs) 1),
wenzelm@20046
   434
                         atac 1]))])])])]);
berghofe@5177
   435
haftmann@26359
   436
        val inj_thms'' = map (fn r => r RS @{thm datatype_injI})
paulson@6171
   437
                             (split_conj_thm inj_thm);
berghofe@5177
   438
paulson@6171
   439
        val elem_thm = 
wenzelm@32970
   440
            Skip_Proof.prove_global thy5 [] [] (HOLogic.mk_Trueprop (mk_conj ind_concl2))
wenzelm@20046
   441
              (fn _ =>
haftmann@32712
   442
               EVERY [(indtac induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
wenzelm@20046
   443
                rewrite_goals_tac rewrites,
wenzelm@20046
   444
                REPEAT ((resolve_tac rep_intrs THEN_ALL_NEW
wenzelm@20046
   445
                  ((REPEAT o etac allE) THEN' ares_tac elem_thms)) 1)]);
berghofe@5177
   446
berghofe@11471
   447
      in (inj_thms'' @ inj_thms, elem_thms @ (split_conj_thm elem_thm))
berghofe@11471
   448
      end;
berghofe@11471
   449
wenzelm@33338
   450
    val (iso_inj_thms_unfolded, iso_elem_thms) =
wenzelm@33338
   451
      fold_rev prove_iso_thms (tl descr) ([], map #3 newT_iso_axms);
berghofe@21021
   452
    val iso_inj_thms = map snd newT_iso_inj_thms @
haftmann@26359
   453
      map (fn r => r RS @{thm injD}) iso_inj_thms_unfolded;
berghofe@11471
   454
berghofe@21021
   455
    (* prove  dt_rep_set_i x --> x : range dt_Rep_i *)
berghofe@11471
   456
berghofe@11471
   457
    fun mk_iso_t (((set_name, iso_name), i), T) =
berghofe@11471
   458
      let val isoT = T --> Univ_elT
berghofe@11471
   459
      in HOLogic.imp $ 
berghofe@21021
   460
        (Const (set_name, UnivT') $ mk_Free "x" Univ_elT i) $
haftmann@31643
   461
          (if i < length newTs then HOLogic.true_const
berghofe@11471
   462
           else HOLogic.mk_mem (mk_Free "x" Univ_elT i,
haftmann@31643
   463
             Const (@{const_name image}, isoT --> HOLogic.mk_setT T --> UnivT) $
haftmann@30304
   464
               Const (iso_name, isoT) $ Const (@{const_name UNIV}, HOLogic.mk_setT T)))
berghofe@5177
   465
      end;
berghofe@5177
   466
berghofe@11471
   467
    val iso_t = HOLogic.mk_Trueprop (mk_conj (map mk_iso_t
berghofe@11471
   468
      (rep_set_names ~~ all_rep_names ~~ (0 upto (length descr' - 1)) ~~ recTs)));
berghofe@11471
   469
berghofe@11471
   470
    (* all the theorems are proved by one single simultaneous induction *)
berghofe@11471
   471
haftmann@26359
   472
    val range_eqs = map (fn r => mk_meta_eq (r RS @{thm range_ex1_eq}))
berghofe@13641
   473
      iso_inj_thms_unfolded;
berghofe@13641
   474
berghofe@11471
   475
    val iso_thms = if length descr = 1 then [] else
skalberg@15570
   476
      Library.drop (length newTs, split_conj_thm
wenzelm@32970
   477
        (Skip_Proof.prove_global thy5 [] [] iso_t (fn _ => EVERY
berghofe@25678
   478
           [(indtac rep_induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
berghofe@11471
   479
            REPEAT (rtac TrueI 1),
berghofe@13641
   480
            rewrite_goals_tac (mk_meta_eq choice_eq ::
haftmann@26359
   481
              symmetric (mk_meta_eq @{thm expand_fun_eq}) :: range_eqs),
berghofe@13641
   482
            rewrite_goals_tac (map symmetric range_eqs),
berghofe@11471
   483
            REPEAT (EVERY
berghofe@13641
   484
              [REPEAT (eresolve_tac ([rangeE, ex1_implies_ex RS exE] @
wenzelm@28362
   485
                 maps (mk_funs_inv thy5 o #1) newT_iso_axms) 1),
berghofe@11471
   486
               TRY (hyp_subst_tac 1),
berghofe@11471
   487
               rtac (sym RS range_eqI) 1,
wenzelm@20046
   488
               resolve_tac iso_char_thms 1])])));
wenzelm@11435
   489
wenzelm@11435
   490
    val Abs_inverse_thms' =
wenzelm@11435
   491
      map #1 newT_iso_axms @
nipkow@33057
   492
      map2 (fn r_inj => fn r => @{thm f_the_inv_into_f} OF [r_inj, r RS mp])
haftmann@18330
   493
        iso_inj_thms_unfolded iso_thms;
wenzelm@11435
   494
wenzelm@28362
   495
    val Abs_inverse_thms = maps (mk_funs_inv thy5) Abs_inverse_thms';
berghofe@5177
   496
berghofe@5177
   497
    (******************* freeness theorems for constructors *******************)
berghofe@5177
   498
haftmann@31668
   499
    val _ = message config "Proving freeness of constructors ...";
berghofe@5177
   500
berghofe@5177
   501
    (* prove theorem  Rep_i (Constr_j ...) = Inj_j ...  *)
berghofe@5177
   502
    
berghofe@5177
   503
    fun prove_constr_rep_thm eqn =
berghofe@5177
   504
      let
berghofe@21021
   505
        val inj_thms = map fst newT_iso_inj_thms;
haftmann@26359
   506
        val rewrites = @{thm o_def} :: constr_defs @ (map (mk_meta_eq o #2) newT_iso_axms)
wenzelm@32970
   507
      in Skip_Proof.prove_global thy5 [] [] eqn (fn _ => EVERY
berghofe@5177
   508
        [resolve_tac inj_thms 1,
berghofe@5177
   509
         rewrite_goals_tac rewrites,
berghofe@21021
   510
         rtac refl 3,
berghofe@5177
   511
         resolve_tac rep_intrs 2,
wenzelm@20046
   512
         REPEAT (resolve_tac iso_elem_thms 1)])
berghofe@5177
   513
      end;
berghofe@5177
   514
berghofe@5177
   515
    (*--------------------------------------------------------------*)
berghofe@5177
   516
    (* constr_rep_thms and rep_congs are used to prove distinctness *)
berghofe@7015
   517
    (* of constructors.                                             *)
berghofe@5177
   518
    (*--------------------------------------------------------------*)
berghofe@5177
   519
berghofe@5177
   520
    val constr_rep_thms = map (map prove_constr_rep_thm) constr_rep_eqns;
berghofe@5177
   521
berghofe@5177
   522
    val dist_rewrites = map (fn (rep_thms, dist_lemma) =>
berghofe@5177
   523
      dist_lemma::(rep_thms @ [In0_eq, In1_eq, In0_not_In1, In1_not_In0]))
berghofe@5177
   524
        (constr_rep_thms ~~ dist_lemmas);
berghofe@5177
   525
haftmann@32900
   526
    fun prove_distinct_thms dist_rewrites' (k, ts) =
haftmann@32900
   527
      let
haftmann@32900
   528
        fun prove [] = []
haftmann@32900
   529
          | prove (t :: ts) =
haftmann@32900
   530
              let
wenzelm@32970
   531
                val dist_thm = Skip_Proof.prove_global thy5 [] [] t (fn _ =>
haftmann@32900
   532
                  EVERY [simp_tac (HOL_ss addsimps dist_rewrites') 1])
wenzelm@32957
   533
              in dist_thm :: Drule.standard (dist_thm RS not_sym) :: prove ts end;
haftmann@32900
   534
      in prove ts end;
berghofe@7015
   535
haftmann@32900
   536
    val distinct_thms = map2 (prove_distinct_thms)
haftmann@32900
   537
      dist_rewrites (DatatypeProp.make_distincts descr sorts);
berghofe@7015
   538
berghofe@5177
   539
    (* prove injectivity of constructors *)
berghofe@5177
   540
berghofe@5177
   541
    fun prove_constr_inj_thm rep_thms t =
berghofe@13641
   542
      let val inj_thms = Scons_inject :: (map make_elim
berghofe@21021
   543
        (iso_inj_thms @
berghofe@13641
   544
          [In0_inject, In1_inject, Leaf_inject, Inl_inject, Inr_inject,
berghofe@13641
   545
           Lim_inject, Suml_inject, Sumr_inject]))
wenzelm@32970
   546
      in Skip_Proof.prove_global thy5 [] [] t (fn _ => EVERY
berghofe@5177
   547
        [rtac iffI 1,
berghofe@5177
   548
         REPEAT (etac conjE 2), hyp_subst_tac 2, rtac refl 2,
berghofe@5177
   549
         dresolve_tac rep_congs 1, dtac box_equals 1,
berghofe@13641
   550
         REPEAT (resolve_tac rep_thms 1),
berghofe@5177
   551
         REPEAT (eresolve_tac inj_thms 1),
berghofe@13641
   552
         REPEAT (ares_tac [conjI] 1 ORELSE (EVERY [REPEAT (rtac ext 1),
berghofe@13641
   553
           REPEAT (eresolve_tac (make_elim fun_cong :: inj_thms) 1),
wenzelm@20046
   554
           atac 1]))])
berghofe@5177
   555
      end;
berghofe@5177
   556
berghofe@5177
   557
    val constr_inject = map (fn (ts, thms) => map (prove_constr_inj_thm thms) ts)
berghofe@5177
   558
      ((DatatypeProp.make_injs descr sorts) ~~ constr_rep_thms);
berghofe@5177
   559
haftmann@18314
   560
    val ((constr_inject', distinct_thms'), thy6) =
haftmann@18314
   561
      thy5
haftmann@32124
   562
      |> Sign.parent_path
haftmann@18314
   563
      |> store_thmss "inject" new_type_names constr_inject
haftmann@18314
   564
      ||>> store_thmss "distinct" new_type_names distinct_thms;
berghofe@5177
   565
berghofe@5177
   566
    (*************************** induction theorem ****************************)
berghofe@5177
   567
haftmann@31668
   568
    val _ = message config "Proving induction rule for datatypes ...";
berghofe@5177
   569
berghofe@5177
   570
    val Rep_inverse_thms = (map (fn (_, iso, _) => iso RS subst) newT_iso_axms) @
berghofe@32999
   571
      (map (fn r => r RS @{thm the_inv_f_f} RS subst) iso_inj_thms_unfolded);
berghofe@32999
   572
    val Rep_inverse_thms' = map (fn r => r RS @{thm the_inv_f_f}) iso_inj_thms_unfolded;
berghofe@5177
   573
wenzelm@33244
   574
    fun mk_indrule_lemma ((i, _), T) (prems, concls) =
berghofe@5177
   575
      let
haftmann@31949
   576
        val Rep_t = Const (nth all_rep_names i, T --> Univ_elT) $
berghofe@5177
   577
          mk_Free "x" T i;
berghofe@5177
   578
berghofe@5177
   579
        val Abs_t = if i < length newTs then
wenzelm@22578
   580
            Const (Sign.intern_const thy6
haftmann@31949
   581
              ("Abs_" ^ (nth new_type_names i)), Univ_elT --> T)
nipkow@33057
   582
          else Const (@{const_name the_inv_into},
berghofe@32999
   583
              [HOLogic.mk_setT T, T --> Univ_elT, Univ_elT] ---> T) $
berghofe@32999
   584
            HOLogic.mk_UNIV T $ Const (nth all_rep_names i, T --> Univ_elT)
berghofe@5177
   585
berghofe@21021
   586
      in (prems @ [HOLogic.imp $
haftmann@31949
   587
            (Const (nth rep_set_names i, UnivT') $ Rep_t) $
berghofe@5177
   588
              (mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ (Abs_t $ Rep_t))],
berghofe@5177
   589
          concls @ [mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ mk_Free "x" T i])
berghofe@5177
   590
      end;
berghofe@5177
   591
berghofe@5177
   592
    val (indrule_lemma_prems, indrule_lemma_concls) =
wenzelm@33244
   593
      fold mk_indrule_lemma (descr' ~~ recTs) ([], []);
berghofe@5177
   594
wenzelm@22578
   595
    val cert = cterm_of thy6;
berghofe@5177
   596
wenzelm@32970
   597
    val indrule_lemma = Skip_Proof.prove_global thy6 [] []
berghofe@5177
   598
      (Logic.mk_implies
berghofe@5177
   599
        (HOLogic.mk_Trueprop (mk_conj indrule_lemma_prems),
wenzelm@17985
   600
         HOLogic.mk_Trueprop (mk_conj indrule_lemma_concls))) (fn _ => EVERY
wenzelm@17985
   601
           [REPEAT (etac conjE 1),
berghofe@5177
   602
            REPEAT (EVERY
berghofe@5177
   603
              [TRY (rtac conjI 1), resolve_tac Rep_inverse_thms 1,
wenzelm@20046
   604
               etac mp 1, resolve_tac iso_elem_thms 1])]);
berghofe@5177
   605
wenzelm@8305
   606
    val Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule_lemma)));
berghofe@5177
   607
    val frees = if length Ps = 1 then [Free ("P", snd (dest_Var (hd Ps)))] else
berghofe@5177
   608
      map (Free o apfst fst o dest_Var) Ps;
berghofe@5177
   609
    val indrule_lemma' = cterm_instantiate (map cert Ps ~~ map cert frees) indrule_lemma;
berghofe@5177
   610
wenzelm@17985
   611
    val dt_induct_prop = DatatypeProp.make_ind descr sorts;
wenzelm@32970
   612
    val dt_induct = Skip_Proof.prove_global thy6 []
wenzelm@17985
   613
      (Logic.strip_imp_prems dt_induct_prop) (Logic.strip_imp_concl dt_induct_prop)
wenzelm@26711
   614
      (fn {prems, ...} => EVERY
berghofe@13641
   615
        [rtac indrule_lemma' 1,
berghofe@25678
   616
         (indtac rep_induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
berghofe@5177
   617
         EVERY (map (fn (prem, r) => (EVERY
berghofe@13641
   618
           [REPEAT (eresolve_tac Abs_inverse_thms 1),
berghofe@5177
   619
            simp_tac (HOL_basic_ss addsimps ((symmetric r)::Rep_inverse_thms')) 1,
berghofe@13641
   620
            DEPTH_SOLVE_1 (ares_tac [prem] 1 ORELSE etac allE 1)]))
wenzelm@20046
   621
                (prems ~~ (constr_defs @ (map mk_meta_eq iso_char_thms))))]);
berghofe@5177
   622
haftmann@18377
   623
    val ([dt_induct'], thy7) =
haftmann@18377
   624
      thy6
wenzelm@24712
   625
      |> Sign.add_path big_name
haftmann@29579
   626
      |> PureThy.add_thms [((Binding.name "induct", dt_induct), [case_names_induct])]
wenzelm@28362
   627
      ||> Sign.parent_path
wenzelm@28362
   628
      ||> Theory.checkpoint;
berghofe@5177
   629
haftmann@18314
   630
  in
haftmann@32907
   631
    ((constr_inject', distinct_thms', dt_induct'), thy7)
berghofe@5177
   632
  end;
berghofe@5177
   633
berghofe@5177
   634
end;