src/HOL/Tools/Datatype/datatype.ML
author wenzelm
Thu Apr 15 15:38:58 2010 +0200 (2010-04-15)
changeset 36148 4ddcc2b07891
parent 35994 9cc3df9a606e
child 36692 54b64d4ad524
permissions -rw-r--r--
spelling;
haftmann@33968
     1
(*  Title:      HOL/Tools/Datatype/datatype.ML
wenzelm@11539
     2
    Author:     Stefan Berghofer, TU Muenchen
berghofe@5177
     3
haftmann@33968
     4
Datatype package: definitional introduction of datatypes
haftmann@33968
     5
with proof of characteristic theorems: injectivity / distinctness
haftmann@33968
     6
of constructors and induction.  Main interface to datatypes
haftmann@33968
     7
after full bootstrap of datatype package.
berghofe@5177
     8
*)
berghofe@5177
     9
haftmann@31723
    10
signature DATATYPE =
wenzelm@6360
    11
sig
haftmann@33963
    12
  include DATATYPE_DATA
haftmann@33968
    13
  val add_datatype : config -> string list -> (string list * binding * mixfix *
haftmann@33968
    14
    (binding * typ list * mixfix) list) list -> theory -> string list * theory
haftmann@33968
    15
  val datatype_cmd : string list -> (string list * binding * mixfix *
haftmann@33968
    16
    (binding * string list * mixfix) list) list -> theory -> theory
haftmann@32717
    17
end;
haftmann@32717
    18
haftmann@33968
    19
structure Datatype : DATATYPE =
haftmann@33963
    20
struct
berghofe@5177
    21
haftmann@33968
    22
(** auxiliary **)
haftmann@33968
    23
haftmann@33968
    24
open Datatype_Aux;
haftmann@33963
    25
open Datatype_Data;
haftmann@33968
    26
haftmann@33968
    27
val (_ $ (_ $ (_ $ (distinct_f $ _) $ _))) = hd (prems_of distinct_lemma);
haftmann@33968
    28
haftmann@33968
    29
val collect_simp = rewrite_rule [mk_meta_eq mem_Collect_eq];
haftmann@33968
    30
haftmann@33968
    31
fun exh_thm_of (dt_info : info Symtab.table) tname =
haftmann@33968
    32
  #exhaust (the (Symtab.lookup dt_info tname));
haftmann@33968
    33
haftmann@33968
    34
val node_name = @{type_name "Datatype.node"};
haftmann@33968
    35
val In0_name = @{const_name "Datatype.In0"};
haftmann@33968
    36
val In1_name = @{const_name "Datatype.In1"};
haftmann@33968
    37
val Scons_name = @{const_name "Datatype.Scons"};
haftmann@33968
    38
val Leaf_name = @{const_name "Datatype.Leaf"};
haftmann@33968
    39
val Lim_name = @{const_name "Datatype.Lim"};
haftmann@33968
    40
val Suml_name = @{const_name "Sum_Type.Suml"};
haftmann@33968
    41
val Sumr_name = @{const_name "Sum_Type.Sumr"};
haftmann@33968
    42
haftmann@33968
    43
val In0_inject = @{thm In0_inject};
haftmann@33968
    44
val In1_inject = @{thm In1_inject};
haftmann@33968
    45
val Scons_inject = @{thm Scons_inject};
haftmann@33968
    46
val Leaf_inject = @{thm Leaf_inject};
haftmann@33968
    47
val In0_eq = @{thm In0_eq};
haftmann@33968
    48
val In1_eq = @{thm In1_eq};
haftmann@33968
    49
val In0_not_In1 = @{thm In0_not_In1};
haftmann@33968
    50
val In1_not_In0 = @{thm In1_not_In0};
haftmann@33968
    51
val Lim_inject = @{thm Lim_inject};
haftmann@33968
    52
val Inl_inject = @{thm Inl_inject};
haftmann@33968
    53
val Inr_inject = @{thm Inr_inject};
haftmann@33968
    54
val Suml_inject = @{thm Suml_inject};
haftmann@33968
    55
val Sumr_inject = @{thm Sumr_inject};
haftmann@33968
    56
haftmann@33968
    57
haftmann@33968
    58
haftmann@33968
    59
(** proof of characteristic theorems **)
haftmann@33968
    60
haftmann@33968
    61
fun representation_proofs (config : config) (dt_info : info Symtab.table)
haftmann@33968
    62
      new_type_names descr sorts types_syntax constr_syntax case_names_induct thy =
haftmann@33968
    63
  let
haftmann@33968
    64
    val descr' = flat descr;
haftmann@33968
    65
    val big_name = space_implode "_" new_type_names;
haftmann@33968
    66
    val thy1 = Sign.add_path big_name thy;
haftmann@33968
    67
    val big_rec_name = big_name ^ "_rep_set";
haftmann@33968
    68
    val rep_set_names' =
haftmann@33968
    69
      (if length descr' = 1 then [big_rec_name] else
haftmann@33968
    70
        (map ((curry (op ^) (big_rec_name ^ "_")) o string_of_int)
haftmann@33968
    71
          (1 upto (length descr'))));
haftmann@33968
    72
    val rep_set_names = map (Sign.full_bname thy1) rep_set_names';
haftmann@33968
    73
haftmann@33968
    74
    val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
haftmann@33968
    75
    val leafTs' = get_nonrec_types descr' sorts;
haftmann@33968
    76
    val branchTs = get_branching_types descr' sorts;
haftmann@33968
    77
    val branchT = if null branchTs then HOLogic.unitT
wenzelm@35364
    78
      else Balanced_Tree.make (fn (T, U) => Type (@{type_name "+"}, [T, U])) branchTs;
haftmann@33968
    79
    val arities = remove (op =) 0 (get_arities descr');
haftmann@33968
    80
    val unneeded_vars =
haftmann@33968
    81
      subtract (op =) (List.foldr OldTerm.add_typ_tfree_names [] (leafTs' @ branchTs)) (hd tyvars);
haftmann@33968
    82
    val leafTs = leafTs' @ map (fn n => TFree (n, (the o AList.lookup (op =) sorts) n)) unneeded_vars;
haftmann@33968
    83
    val recTs = get_rec_types descr' sorts;
haftmann@33968
    84
    val (newTs, oldTs) = chop (length (hd descr)) recTs;
haftmann@33968
    85
    val sumT = if null leafTs then HOLogic.unitT
wenzelm@35364
    86
      else Balanced_Tree.make (fn (T, U) => Type (@{type_name "+"}, [T, U])) leafTs;
haftmann@33968
    87
    val Univ_elT = HOLogic.mk_setT (Type (node_name, [sumT, branchT]));
haftmann@33968
    88
    val UnivT = HOLogic.mk_setT Univ_elT;
haftmann@33968
    89
    val UnivT' = Univ_elT --> HOLogic.boolT;
haftmann@33968
    90
    val Collect = Const (@{const_name Collect}, UnivT' --> UnivT);
haftmann@33968
    91
haftmann@33968
    92
    val In0 = Const (In0_name, Univ_elT --> Univ_elT);
haftmann@33968
    93
    val In1 = Const (In1_name, Univ_elT --> Univ_elT);
haftmann@33968
    94
    val Leaf = Const (Leaf_name, sumT --> Univ_elT);
haftmann@33968
    95
    val Lim = Const (Lim_name, (branchT --> Univ_elT) --> Univ_elT);
haftmann@33968
    96
haftmann@33968
    97
    (* make injections needed for embedding types in leaves *)
haftmann@33968
    98
haftmann@33968
    99
    fun mk_inj T' x =
haftmann@33968
   100
      let
haftmann@33968
   101
        fun mk_inj' T n i =
haftmann@33968
   102
          if n = 1 then x else
haftmann@33968
   103
          let val n2 = n div 2;
haftmann@33968
   104
              val Type (_, [T1, T2]) = T
haftmann@33968
   105
          in
haftmann@33968
   106
            if i <= n2 then
wenzelm@35364
   107
              Const (@{const_name Inl}, T1 --> T) $ (mk_inj' T1 n2 i)
haftmann@33968
   108
            else
wenzelm@35364
   109
              Const (@{const_name Inr}, T2 --> T) $ (mk_inj' T2 (n - n2) (i - n2))
haftmann@33968
   110
          end
haftmann@33968
   111
      in mk_inj' sumT (length leafTs) (1 + find_index (fn T'' => T'' = T') leafTs)
haftmann@33968
   112
      end;
haftmann@33968
   113
haftmann@33968
   114
    (* make injections for constructors *)
haftmann@33968
   115
haftmann@33968
   116
    fun mk_univ_inj ts = Balanced_Tree.access
haftmann@33968
   117
      {left = fn t => In0 $ t,
haftmann@33968
   118
        right = fn t => In1 $ t,
haftmann@33968
   119
        init =
haftmann@33968
   120
          if ts = [] then Const (@{const_name undefined}, Univ_elT)
haftmann@33968
   121
          else foldr1 (HOLogic.mk_binop Scons_name) ts};
haftmann@33968
   122
haftmann@33968
   123
    (* function spaces *)
haftmann@33968
   124
haftmann@33968
   125
    fun mk_fun_inj T' x =
haftmann@33968
   126
      let
haftmann@33968
   127
        fun mk_inj T n i =
haftmann@33968
   128
          if n = 1 then x else
haftmann@33968
   129
          let
haftmann@33968
   130
            val n2 = n div 2;
haftmann@33968
   131
            val Type (_, [T1, T2]) = T;
haftmann@33968
   132
            fun mkT U = (U --> Univ_elT) --> T --> Univ_elT
haftmann@33968
   133
          in
haftmann@33968
   134
            if i <= n2 then Const (Suml_name, mkT T1) $ mk_inj T1 n2 i
haftmann@33968
   135
            else Const (Sumr_name, mkT T2) $ mk_inj T2 (n - n2) (i - n2)
haftmann@33968
   136
          end
haftmann@33968
   137
      in mk_inj branchT (length branchTs) (1 + find_index (fn T'' => T'' = T') branchTs)
haftmann@33968
   138
      end;
haftmann@33968
   139
haftmann@33968
   140
    fun mk_lim t Ts = fold_rev (fn T => fn t => Lim $ mk_fun_inj T (Abs ("x", T, t))) Ts t;
haftmann@33968
   141
haftmann@33968
   142
    (************** generate introduction rules for representing set **********)
haftmann@33968
   143
haftmann@33968
   144
    val _ = message config "Constructing representing sets ...";
haftmann@33968
   145
haftmann@33968
   146
    (* make introduction rule for a single constructor *)
haftmann@33968
   147
haftmann@33968
   148
    fun make_intr s n (i, (_, cargs)) =
haftmann@33968
   149
      let
haftmann@33968
   150
        fun mk_prem dt (j, prems, ts) =
haftmann@33968
   151
          (case strip_dtyp dt of
haftmann@33968
   152
            (dts, DtRec k) =>
haftmann@33968
   153
              let
haftmann@33968
   154
                val Ts = map (typ_of_dtyp descr' sorts) dts;
haftmann@33968
   155
                val free_t =
haftmann@33968
   156
                  app_bnds (mk_Free "x" (Ts ---> Univ_elT) j) (length Ts)
haftmann@33968
   157
              in (j + 1, list_all (map (pair "x") Ts,
haftmann@33968
   158
                  HOLogic.mk_Trueprop
haftmann@33968
   159
                    (Free (nth rep_set_names' k, UnivT') $ free_t)) :: prems,
haftmann@33968
   160
                mk_lim free_t Ts :: ts)
haftmann@33968
   161
              end
haftmann@33968
   162
          | _ =>
haftmann@33968
   163
              let val T = typ_of_dtyp descr' sorts dt
haftmann@33968
   164
              in (j + 1, prems, (Leaf $ mk_inj T (mk_Free "x" T j))::ts)
haftmann@33968
   165
              end);
haftmann@33968
   166
haftmann@33968
   167
        val (_, prems, ts) = fold_rev mk_prem cargs (1, [], []);
haftmann@33968
   168
        val concl = HOLogic.mk_Trueprop
haftmann@33968
   169
          (Free (s, UnivT') $ mk_univ_inj ts n i)
haftmann@33968
   170
      in Logic.list_implies (prems, concl)
haftmann@33968
   171
      end;
haftmann@33968
   172
haftmann@33968
   173
    val intr_ts = maps (fn ((_, (_, _, constrs)), rep_set_name) =>
haftmann@33968
   174
      map (make_intr rep_set_name (length constrs))
haftmann@33968
   175
        ((1 upto (length constrs)) ~~ constrs)) (descr' ~~ rep_set_names');
haftmann@33968
   176
haftmann@33968
   177
    val ({raw_induct = rep_induct, intrs = rep_intrs, ...}, thy2) =
haftmann@33968
   178
      thy1
haftmann@33968
   179
      |> Sign.map_naming Name_Space.conceal
haftmann@33968
   180
      |> Inductive.add_inductive_global
haftmann@33968
   181
          {quiet_mode = #quiet config, verbose = false, alt_name = Binding.name big_rec_name,
haftmann@33968
   182
           coind = false, no_elim = true, no_ind = false, skip_mono = true, fork_mono = false}
haftmann@33968
   183
          (map (fn s => ((Binding.name s, UnivT'), NoSyn)) rep_set_names') []
haftmann@33968
   184
          (map (fn x => (Attrib.empty_binding, x)) intr_ts) []
haftmann@33968
   185
      ||> Sign.restore_naming thy1
haftmann@33968
   186
      ||> Theory.checkpoint;
haftmann@33968
   187
haftmann@33968
   188
    (********************************* typedef ********************************)
haftmann@33968
   189
haftmann@33968
   190
    val (typedefs, thy3) = thy2 |>
haftmann@33968
   191
      Sign.parent_path |>
haftmann@33968
   192
      fold_map (fn ((((name, mx), tvs), c), name') =>
wenzelm@35842
   193
          Typedef.add_typedef_global false (SOME (Binding.name name'))
wenzelm@35842
   194
            (name, map (rpair dummyS) tvs, mx)
haftmann@33968
   195
            (Collect $ Const (c, UnivT')) NONE
haftmann@33968
   196
            (rtac exI 1 THEN rtac CollectI 1 THEN
haftmann@33968
   197
              QUIET_BREADTH_FIRST (has_fewer_prems 1)
haftmann@33968
   198
              (resolve_tac rep_intrs 1)))
haftmann@33968
   199
                (types_syntax ~~ tyvars ~~
haftmann@33968
   200
                  (take (length newTs) rep_set_names) ~~ new_type_names) ||>
haftmann@33968
   201
      Sign.add_path big_name;
haftmann@33968
   202
haftmann@33968
   203
    (*********************** definition of constructors ***********************)
haftmann@33968
   204
haftmann@33968
   205
    val big_rep_name = (space_implode "_" new_type_names) ^ "_Rep_";
haftmann@33968
   206
    val rep_names = map (curry op ^ "Rep_") new_type_names;
haftmann@33968
   207
    val rep_names' = map (fn i => big_rep_name ^ (string_of_int i))
haftmann@33968
   208
      (1 upto (length (flat (tl descr))));
haftmann@33968
   209
    val all_rep_names = map (Sign.intern_const thy3) rep_names @
haftmann@33968
   210
      map (Sign.full_bname thy3) rep_names';
haftmann@33968
   211
haftmann@33968
   212
    (* isomorphism declarations *)
haftmann@33968
   213
haftmann@33968
   214
    val iso_decls = map (fn (T, s) => (Binding.name s, T --> Univ_elT, NoSyn))
haftmann@33968
   215
      (oldTs ~~ rep_names');
haftmann@33968
   216
haftmann@33968
   217
    (* constructor definitions *)
haftmann@33968
   218
haftmann@33968
   219
    fun make_constr_def tname T n ((cname, cargs), (cname', mx)) (thy, defs, eqns, i) =
haftmann@33968
   220
      let
haftmann@33968
   221
        fun constr_arg dt (j, l_args, r_args) =
haftmann@33968
   222
          let val T = typ_of_dtyp descr' sorts dt;
haftmann@33968
   223
              val free_t = mk_Free "x" T j
haftmann@33968
   224
          in (case (strip_dtyp dt, strip_type T) of
haftmann@33968
   225
              ((_, DtRec m), (Us, U)) => (j + 1, free_t :: l_args, mk_lim
haftmann@33968
   226
                (Const (nth all_rep_names m, U --> Univ_elT) $
haftmann@33968
   227
                   app_bnds free_t (length Us)) Us :: r_args)
haftmann@33968
   228
            | _ => (j + 1, free_t::l_args, (Leaf $ mk_inj T free_t)::r_args))
haftmann@33968
   229
          end;
haftmann@33968
   230
haftmann@33968
   231
        val (_, l_args, r_args) = fold_rev constr_arg cargs (1, [], []);
haftmann@33968
   232
        val constrT = (map (typ_of_dtyp descr' sorts) cargs) ---> T;
haftmann@33968
   233
        val abs_name = Sign.intern_const thy ("Abs_" ^ tname);
haftmann@33968
   234
        val rep_name = Sign.intern_const thy ("Rep_" ^ tname);
haftmann@33968
   235
        val lhs = list_comb (Const (cname, constrT), l_args);
haftmann@33968
   236
        val rhs = mk_univ_inj r_args n i;
haftmann@33968
   237
        val def = Logic.mk_equals (lhs, Const (abs_name, Univ_elT --> T) $ rhs);
haftmann@33968
   238
        val def_name = Long_Name.base_name cname ^ "_def";
haftmann@33968
   239
        val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
haftmann@33968
   240
          (Const (rep_name, T --> Univ_elT) $ lhs, rhs));
haftmann@33968
   241
        val ([def_thm], thy') =
haftmann@33968
   242
          thy
haftmann@33968
   243
          |> Sign.add_consts_i [(cname', constrT, mx)]
haftmann@33968
   244
          |> (PureThy.add_defs false o map Thm.no_attributes) [(Binding.name def_name, def)];
haftmann@33968
   245
haftmann@33968
   246
      in (thy', defs @ [def_thm], eqns @ [eqn], i + 1) end;
haftmann@33968
   247
haftmann@33968
   248
    (* constructor definitions for datatype *)
haftmann@33968
   249
haftmann@33968
   250
    fun dt_constr_defs ((((_, (_, _, constrs)), tname), T), constr_syntax)
haftmann@33968
   251
        (thy, defs, eqns, rep_congs, dist_lemmas) =
haftmann@33968
   252
      let
haftmann@33968
   253
        val _ $ (_ $ (cong_f $ _) $ _) = concl_of arg_cong;
haftmann@33968
   254
        val rep_const = cterm_of thy
haftmann@33968
   255
          (Const (Sign.intern_const thy ("Rep_" ^ tname), T --> Univ_elT));
haftmann@33968
   256
        val cong' =
wenzelm@35021
   257
          Drule.export_without_context
wenzelm@35021
   258
            (cterm_instantiate [(cterm_of thy cong_f, rep_const)] arg_cong);
haftmann@33968
   259
        val dist =
wenzelm@35021
   260
          Drule.export_without_context
wenzelm@35021
   261
            (cterm_instantiate [(cterm_of thy distinct_f, rep_const)] distinct_lemma);
haftmann@33968
   262
        val (thy', defs', eqns', _) = fold ((make_constr_def tname T) (length constrs))
haftmann@33968
   263
          (constrs ~~ constr_syntax) (Sign.add_path tname thy, defs, [], 1);
haftmann@33968
   264
      in
haftmann@33968
   265
        (Sign.parent_path thy', defs', eqns @ [eqns'],
haftmann@33968
   266
          rep_congs @ [cong'], dist_lemmas @ [dist])
haftmann@33968
   267
      end;
haftmann@33968
   268
haftmann@33968
   269
    val (thy4, constr_defs, constr_rep_eqns, rep_congs, dist_lemmas) =
haftmann@33968
   270
      fold dt_constr_defs
haftmann@33968
   271
        (hd descr ~~ new_type_names ~~ newTs ~~ constr_syntax)
haftmann@33968
   272
        (thy3 |> Sign.add_consts_i iso_decls |> Sign.parent_path, [], [], [], []);
haftmann@33968
   273
haftmann@33968
   274
haftmann@33968
   275
    (*********** isomorphisms for new types (introduced by typedef) ***********)
haftmann@33968
   276
haftmann@33968
   277
    val _ = message config "Proving isomorphism properties ...";
haftmann@33968
   278
wenzelm@35994
   279
    val newT_iso_axms = map (fn (_, (_, td)) =>
haftmann@33968
   280
      (collect_simp (#Abs_inverse td), #Rep_inverse td,
haftmann@33968
   281
       collect_simp (#Rep td))) typedefs;
haftmann@33968
   282
wenzelm@35994
   283
    val newT_iso_inj_thms = map (fn (_, (_, td)) =>
haftmann@33968
   284
      (collect_simp (#Abs_inject td) RS iffD1, #Rep_inject td RS iffD1)) typedefs;
haftmann@33968
   285
haftmann@33968
   286
    (********* isomorphisms between existing types and "unfolded" types *******)
haftmann@33968
   287
haftmann@33968
   288
    (*---------------------------------------------------------------------*)
haftmann@33968
   289
    (* isomorphisms are defined using primrec-combinators:                 *)
haftmann@33968
   290
    (* generate appropriate functions for instantiating primrec-combinator *)
haftmann@33968
   291
    (*                                                                     *)
haftmann@33968
   292
    (*   e.g.  dt_Rep_i = list_rec ... (%h t y. In1 (Scons (Leaf h) y))    *)
haftmann@33968
   293
    (*                                                                     *)
haftmann@33968
   294
    (* also generate characteristic equations for isomorphisms             *)
haftmann@33968
   295
    (*                                                                     *)
haftmann@33968
   296
    (*   e.g.  dt_Rep_i (cons h t) = In1 (Scons (dt_Rep_j h) (dt_Rep_i t)) *)
haftmann@33968
   297
    (*---------------------------------------------------------------------*)
haftmann@33968
   298
haftmann@33968
   299
    fun make_iso_def k ks n (cname, cargs) (fs, eqns, i) =
haftmann@33968
   300
      let
haftmann@33968
   301
        val argTs = map (typ_of_dtyp descr' sorts) cargs;
haftmann@33968
   302
        val T = nth recTs k;
haftmann@33968
   303
        val rep_name = nth all_rep_names k;
haftmann@33968
   304
        val rep_const = Const (rep_name, T --> Univ_elT);
haftmann@33968
   305
        val constr = Const (cname, argTs ---> T);
haftmann@33968
   306
haftmann@33968
   307
        fun process_arg ks' dt (i2, i2', ts, Ts) =
haftmann@33968
   308
          let
haftmann@33968
   309
            val T' = typ_of_dtyp descr' sorts dt;
haftmann@33968
   310
            val (Us, U) = strip_type T'
haftmann@33968
   311
          in (case strip_dtyp dt of
haftmann@33968
   312
              (_, DtRec j) => if j mem ks' then
haftmann@33968
   313
                  (i2 + 1, i2' + 1, ts @ [mk_lim (app_bnds
haftmann@33968
   314
                     (mk_Free "y" (Us ---> Univ_elT) i2') (length Us)) Us],
haftmann@33968
   315
                   Ts @ [Us ---> Univ_elT])
haftmann@33968
   316
                else
haftmann@33968
   317
                  (i2 + 1, i2', ts @ [mk_lim
haftmann@33968
   318
                     (Const (nth all_rep_names j, U --> Univ_elT) $
haftmann@33968
   319
                        app_bnds (mk_Free "x" T' i2) (length Us)) Us], Ts)
haftmann@33968
   320
            | _ => (i2 + 1, i2', ts @ [Leaf $ mk_inj T' (mk_Free "x" T' i2)], Ts))
haftmann@33968
   321
          end;
haftmann@33968
   322
haftmann@33968
   323
        val (i2, i2', ts, Ts) = fold (process_arg ks) cargs (1, 1, [], []);
haftmann@33968
   324
        val xs = map (uncurry (mk_Free "x")) (argTs ~~ (1 upto (i2 - 1)));
haftmann@33968
   325
        val ys = map (uncurry (mk_Free "y")) (Ts ~~ (1 upto (i2' - 1)));
haftmann@33968
   326
        val f = list_abs_free (map dest_Free (xs @ ys), mk_univ_inj ts n i);
haftmann@33968
   327
haftmann@33968
   328
        val (_, _, ts', _) = fold (process_arg []) cargs (1, 1, [], []);
haftmann@33968
   329
        val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
haftmann@33968
   330
          (rep_const $ list_comb (constr, xs), mk_univ_inj ts' n i))
haftmann@33968
   331
haftmann@33968
   332
      in (fs @ [f], eqns @ [eqn], i + 1) end;
haftmann@33968
   333
haftmann@33968
   334
    (* define isomorphisms for all mutually recursive datatypes in list ds *)
haftmann@33968
   335
haftmann@33968
   336
    fun make_iso_defs ds (thy, char_thms) =
haftmann@33968
   337
      let
haftmann@33968
   338
        val ks = map fst ds;
haftmann@33968
   339
        val (_, (tname, _, _)) = hd ds;
haftmann@33968
   340
        val {rec_rewrites, rec_names, ...} = the (Symtab.lookup dt_info tname);
haftmann@33968
   341
haftmann@33968
   342
        fun process_dt (k, (tname, _, constrs)) (fs, eqns, isos) =
haftmann@33968
   343
          let
haftmann@33968
   344
            val (fs', eqns', _) =
haftmann@33968
   345
              fold (make_iso_def k ks (length constrs)) constrs (fs, eqns, 1);
haftmann@33968
   346
            val iso = (nth recTs k, nth all_rep_names k)
haftmann@33968
   347
          in (fs', eqns', isos @ [iso]) end;
haftmann@33968
   348
        
haftmann@33968
   349
        val (fs, eqns, isos) = fold process_dt ds ([], [], []);
haftmann@33968
   350
        val fTs = map fastype_of fs;
haftmann@33968
   351
        val defs = map (fn (rec_name, (T, iso_name)) => (Binding.name (Long_Name.base_name iso_name ^ "_def"),
haftmann@33968
   352
          Logic.mk_equals (Const (iso_name, T --> Univ_elT),
haftmann@33968
   353
            list_comb (Const (rec_name, fTs @ [T] ---> Univ_elT), fs)))) (rec_names ~~ isos);
haftmann@33968
   354
        val (def_thms, thy') =
haftmann@33968
   355
          apsnd Theory.checkpoint ((PureThy.add_defs false o map Thm.no_attributes) defs thy);
haftmann@33968
   356
haftmann@33968
   357
        (* prove characteristic equations *)
haftmann@33968
   358
haftmann@33968
   359
        val rewrites = def_thms @ (map mk_meta_eq rec_rewrites);
haftmann@33968
   360
        val char_thms' = map (fn eqn => Skip_Proof.prove_global thy' [] [] eqn
haftmann@33968
   361
          (fn _ => EVERY [rewrite_goals_tac rewrites, rtac refl 1])) eqns;
haftmann@33968
   362
haftmann@33968
   363
      in (thy', char_thms' @ char_thms) end;
haftmann@33968
   364
haftmann@33968
   365
    val (thy5, iso_char_thms) = apfst Theory.checkpoint (fold_rev make_iso_defs
haftmann@33968
   366
        (tl descr) (Sign.add_path big_name thy4, []));
haftmann@33968
   367
haftmann@33968
   368
    (* prove isomorphism properties *)
haftmann@33968
   369
haftmann@33968
   370
    fun mk_funs_inv thy thm =
haftmann@33968
   371
      let
haftmann@33968
   372
        val prop = Thm.prop_of thm;
haftmann@33968
   373
        val _ $ (_ $ ((S as Const (_, Type (_, [U, _]))) $ _ )) $
haftmann@33968
   374
          (_ $ (_ $ (r $ (a $ _)) $ _)) = Type.legacy_freeze prop;
haftmann@33968
   375
        val used = OldTerm.add_term_tfree_names (a, []);
haftmann@33968
   376
haftmann@33968
   377
        fun mk_thm i =
haftmann@33968
   378
          let
haftmann@33968
   379
            val Ts = map (TFree o rpair HOLogic.typeS)
haftmann@33968
   380
              (Name.variant_list used (replicate i "'t"));
haftmann@33968
   381
            val f = Free ("f", Ts ---> U)
haftmann@33968
   382
          in Skip_Proof.prove_global thy [] [] (Logic.mk_implies
haftmann@33968
   383
            (HOLogic.mk_Trueprop (HOLogic.list_all
haftmann@33968
   384
               (map (pair "x") Ts, S $ app_bnds f i)),
haftmann@33968
   385
             HOLogic.mk_Trueprop (HOLogic.mk_eq (list_abs (map (pair "x") Ts,
haftmann@33968
   386
               r $ (a $ app_bnds f i)), f))))
haftmann@33968
   387
            (fn _ => EVERY [REPEAT_DETERM_N i (rtac ext 1),
haftmann@33968
   388
               REPEAT (etac allE 1), rtac thm 1, atac 1])
haftmann@33968
   389
          end
haftmann@33968
   390
      in map (fn r => r RS subst) (thm :: map mk_thm arities) end;
haftmann@33968
   391
haftmann@33968
   392
    (* prove  inj dt_Rep_i  and  dt_Rep_i x : dt_rep_set_i *)
haftmann@33968
   393
haftmann@33968
   394
    val fun_congs = map (fn T => make_elim (Drule.instantiate'
haftmann@33968
   395
      [SOME (ctyp_of thy5 T)] [] fun_cong)) branchTs;
haftmann@33968
   396
haftmann@33968
   397
    fun prove_iso_thms ds (inj_thms, elem_thms) =
haftmann@33968
   398
      let
haftmann@33968
   399
        val (_, (tname, _, _)) = hd ds;
haftmann@33968
   400
        val induct = (#induct o the o Symtab.lookup dt_info) tname;
haftmann@33968
   401
haftmann@33968
   402
        fun mk_ind_concl (i, _) =
haftmann@33968
   403
          let
haftmann@33968
   404
            val T = nth recTs i;
haftmann@33968
   405
            val Rep_t = Const (nth all_rep_names i, T --> Univ_elT);
haftmann@33968
   406
            val rep_set_name = nth rep_set_names i
haftmann@33968
   407
          in (HOLogic.all_const T $ Abs ("y", T, HOLogic.imp $
haftmann@33968
   408
                HOLogic.mk_eq (Rep_t $ mk_Free "x" T i, Rep_t $ Bound 0) $
haftmann@33968
   409
                  HOLogic.mk_eq (mk_Free "x" T i, Bound 0)),
haftmann@33968
   410
              Const (rep_set_name, UnivT') $ (Rep_t $ mk_Free "x" T i))
haftmann@33968
   411
          end;
haftmann@33968
   412
haftmann@33968
   413
        val (ind_concl1, ind_concl2) = ListPair.unzip (map mk_ind_concl ds);
haftmann@33968
   414
haftmann@33968
   415
        val rewrites = map mk_meta_eq iso_char_thms;
haftmann@33968
   416
        val inj_thms' = map snd newT_iso_inj_thms @
haftmann@33968
   417
          map (fn r => r RS @{thm injD}) inj_thms;
haftmann@33968
   418
haftmann@33968
   419
        val inj_thm = Skip_Proof.prove_global thy5 [] []
haftmann@33968
   420
          (HOLogic.mk_Trueprop (mk_conj ind_concl1)) (fn _ => EVERY
wenzelm@35625
   421
            [(indtac induct [] THEN_ALL_NEW Object_Logic.atomize_prems_tac) 1,
haftmann@33968
   422
             REPEAT (EVERY
haftmann@33968
   423
               [rtac allI 1, rtac impI 1,
haftmann@33968
   424
                exh_tac (exh_thm_of dt_info) 1,
haftmann@33968
   425
                REPEAT (EVERY
haftmann@33968
   426
                  [hyp_subst_tac 1,
haftmann@33968
   427
                   rewrite_goals_tac rewrites,
haftmann@33968
   428
                   REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
haftmann@33968
   429
                   (eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1)
haftmann@33968
   430
                   ORELSE (EVERY
haftmann@33968
   431
                     [REPEAT (eresolve_tac (Scons_inject ::
haftmann@33968
   432
                        map make_elim [Leaf_inject, Inl_inject, Inr_inject]) 1),
haftmann@33968
   433
                      REPEAT (cong_tac 1), rtac refl 1,
haftmann@33968
   434
                      REPEAT (atac 1 ORELSE (EVERY
haftmann@33968
   435
                        [REPEAT (rtac ext 1),
haftmann@33968
   436
                         REPEAT (eresolve_tac (mp :: allE ::
haftmann@33968
   437
                           map make_elim (Suml_inject :: Sumr_inject ::
haftmann@33968
   438
                             Lim_inject :: inj_thms') @ fun_congs) 1),
haftmann@33968
   439
                         atac 1]))])])])]);
haftmann@33968
   440
haftmann@33968
   441
        val inj_thms'' = map (fn r => r RS @{thm datatype_injI})
haftmann@33968
   442
                             (split_conj_thm inj_thm);
haftmann@33968
   443
haftmann@33968
   444
        val elem_thm = 
haftmann@33968
   445
            Skip_Proof.prove_global thy5 [] [] (HOLogic.mk_Trueprop (mk_conj ind_concl2))
haftmann@33968
   446
              (fn _ =>
wenzelm@35625
   447
               EVERY [(indtac induct [] THEN_ALL_NEW Object_Logic.atomize_prems_tac) 1,
haftmann@33968
   448
                rewrite_goals_tac rewrites,
haftmann@33968
   449
                REPEAT ((resolve_tac rep_intrs THEN_ALL_NEW
haftmann@33968
   450
                  ((REPEAT o etac allE) THEN' ares_tac elem_thms)) 1)]);
haftmann@33968
   451
haftmann@33968
   452
      in (inj_thms'' @ inj_thms, elem_thms @ (split_conj_thm elem_thm))
haftmann@33968
   453
      end;
haftmann@33968
   454
haftmann@33968
   455
    val (iso_inj_thms_unfolded, iso_elem_thms) =
haftmann@33968
   456
      fold_rev prove_iso_thms (tl descr) ([], map #3 newT_iso_axms);
haftmann@33968
   457
    val iso_inj_thms = map snd newT_iso_inj_thms @
haftmann@33968
   458
      map (fn r => r RS @{thm injD}) iso_inj_thms_unfolded;
haftmann@33968
   459
haftmann@33968
   460
    (* prove  dt_rep_set_i x --> x : range dt_Rep_i *)
haftmann@33968
   461
haftmann@33968
   462
    fun mk_iso_t (((set_name, iso_name), i), T) =
haftmann@33968
   463
      let val isoT = T --> Univ_elT
haftmann@33968
   464
      in HOLogic.imp $ 
haftmann@33968
   465
        (Const (set_name, UnivT') $ mk_Free "x" Univ_elT i) $
haftmann@33968
   466
          (if i < length newTs then HOLogic.true_const
haftmann@33968
   467
           else HOLogic.mk_mem (mk_Free "x" Univ_elT i,
haftmann@33968
   468
             Const (@{const_name image}, isoT --> HOLogic.mk_setT T --> UnivT) $
wenzelm@35402
   469
               Const (iso_name, isoT) $ Const (@{const_abbrev UNIV}, HOLogic.mk_setT T)))
haftmann@33968
   470
      end;
haftmann@33968
   471
haftmann@33968
   472
    val iso_t = HOLogic.mk_Trueprop (mk_conj (map mk_iso_t
haftmann@33968
   473
      (rep_set_names ~~ all_rep_names ~~ (0 upto (length descr' - 1)) ~~ recTs)));
haftmann@33968
   474
haftmann@33968
   475
    (* all the theorems are proved by one single simultaneous induction *)
haftmann@33968
   476
haftmann@33968
   477
    val range_eqs = map (fn r => mk_meta_eq (r RS @{thm range_ex1_eq}))
haftmann@33968
   478
      iso_inj_thms_unfolded;
haftmann@33968
   479
haftmann@33968
   480
    val iso_thms = if length descr = 1 then [] else
haftmann@33968
   481
      drop (length newTs) (split_conj_thm
haftmann@33968
   482
        (Skip_Proof.prove_global thy5 [] [] iso_t (fn _ => EVERY
wenzelm@35625
   483
           [(indtac rep_induct [] THEN_ALL_NEW Object_Logic.atomize_prems_tac) 1,
haftmann@33968
   484
            REPEAT (rtac TrueI 1),
wenzelm@35410
   485
            rewrite_goals_tac (mk_meta_eq @{thm choice_eq} ::
haftmann@33968
   486
              symmetric (mk_meta_eq @{thm expand_fun_eq}) :: range_eqs),
haftmann@33968
   487
            rewrite_goals_tac (map symmetric range_eqs),
haftmann@33968
   488
            REPEAT (EVERY
haftmann@33968
   489
              [REPEAT (eresolve_tac ([rangeE, ex1_implies_ex RS exE] @
haftmann@33968
   490
                 maps (mk_funs_inv thy5 o #1) newT_iso_axms) 1),
haftmann@33968
   491
               TRY (hyp_subst_tac 1),
haftmann@33968
   492
               rtac (sym RS range_eqI) 1,
haftmann@33968
   493
               resolve_tac iso_char_thms 1])])));
haftmann@33968
   494
haftmann@33968
   495
    val Abs_inverse_thms' =
haftmann@33968
   496
      map #1 newT_iso_axms @
haftmann@33968
   497
      map2 (fn r_inj => fn r => @{thm f_the_inv_into_f} OF [r_inj, r RS mp])
haftmann@33968
   498
        iso_inj_thms_unfolded iso_thms;
haftmann@33968
   499
haftmann@33968
   500
    val Abs_inverse_thms = maps (mk_funs_inv thy5) Abs_inverse_thms';
haftmann@33968
   501
haftmann@33968
   502
    (******************* freeness theorems for constructors *******************)
haftmann@33968
   503
haftmann@33968
   504
    val _ = message config "Proving freeness of constructors ...";
haftmann@33968
   505
haftmann@33968
   506
    (* prove theorem  Rep_i (Constr_j ...) = Inj_j ...  *)
haftmann@33968
   507
    
haftmann@33968
   508
    fun prove_constr_rep_thm eqn =
haftmann@33968
   509
      let
haftmann@33968
   510
        val inj_thms = map fst newT_iso_inj_thms;
haftmann@33968
   511
        val rewrites = @{thm o_def} :: constr_defs @ (map (mk_meta_eq o #2) newT_iso_axms)
haftmann@33968
   512
      in Skip_Proof.prove_global thy5 [] [] eqn (fn _ => EVERY
haftmann@33968
   513
        [resolve_tac inj_thms 1,
haftmann@33968
   514
         rewrite_goals_tac rewrites,
haftmann@33968
   515
         rtac refl 3,
haftmann@33968
   516
         resolve_tac rep_intrs 2,
haftmann@33968
   517
         REPEAT (resolve_tac iso_elem_thms 1)])
haftmann@33968
   518
      end;
haftmann@33968
   519
haftmann@33968
   520
    (*--------------------------------------------------------------*)
haftmann@33968
   521
    (* constr_rep_thms and rep_congs are used to prove distinctness *)
haftmann@33968
   522
    (* of constructors.                                             *)
haftmann@33968
   523
    (*--------------------------------------------------------------*)
haftmann@33968
   524
haftmann@33968
   525
    val constr_rep_thms = map (map prove_constr_rep_thm) constr_rep_eqns;
haftmann@33968
   526
haftmann@33968
   527
    val dist_rewrites = map (fn (rep_thms, dist_lemma) =>
haftmann@33968
   528
      dist_lemma::(rep_thms @ [In0_eq, In1_eq, In0_not_In1, In1_not_In0]))
haftmann@33968
   529
        (constr_rep_thms ~~ dist_lemmas);
haftmann@33968
   530
haftmann@33968
   531
    fun prove_distinct_thms dist_rewrites' (k, ts) =
haftmann@33968
   532
      let
haftmann@33968
   533
        fun prove [] = []
haftmann@33968
   534
          | prove (t :: ts) =
haftmann@33968
   535
              let
haftmann@33968
   536
                val dist_thm = Skip_Proof.prove_global thy5 [] [] t (fn _ =>
haftmann@33968
   537
                  EVERY [simp_tac (HOL_ss addsimps dist_rewrites') 1])
wenzelm@35021
   538
              in dist_thm :: Drule.export_without_context (dist_thm RS not_sym) :: prove ts end;
haftmann@33968
   539
      in prove ts end;
haftmann@33968
   540
haftmann@33968
   541
    val distinct_thms = map2 (prove_distinct_thms)
haftmann@33968
   542
      dist_rewrites (Datatype_Prop.make_distincts descr sorts);
haftmann@33968
   543
haftmann@33968
   544
    (* prove injectivity of constructors *)
haftmann@33968
   545
haftmann@33968
   546
    fun prove_constr_inj_thm rep_thms t =
haftmann@33968
   547
      let val inj_thms = Scons_inject :: (map make_elim
haftmann@33968
   548
        (iso_inj_thms @
haftmann@33968
   549
          [In0_inject, In1_inject, Leaf_inject, Inl_inject, Inr_inject,
haftmann@33968
   550
           Lim_inject, Suml_inject, Sumr_inject]))
haftmann@33968
   551
      in Skip_Proof.prove_global thy5 [] [] t (fn _ => EVERY
haftmann@33968
   552
        [rtac iffI 1,
haftmann@33968
   553
         REPEAT (etac conjE 2), hyp_subst_tac 2, rtac refl 2,
haftmann@33968
   554
         dresolve_tac rep_congs 1, dtac box_equals 1,
haftmann@33968
   555
         REPEAT (resolve_tac rep_thms 1),
haftmann@33968
   556
         REPEAT (eresolve_tac inj_thms 1),
haftmann@33968
   557
         REPEAT (ares_tac [conjI] 1 ORELSE (EVERY [REPEAT (rtac ext 1),
haftmann@33968
   558
           REPEAT (eresolve_tac (make_elim fun_cong :: inj_thms) 1),
haftmann@33968
   559
           atac 1]))])
haftmann@33968
   560
      end;
haftmann@33968
   561
haftmann@33968
   562
    val constr_inject = map (fn (ts, thms) => map (prove_constr_inj_thm thms) ts)
haftmann@33968
   563
      ((Datatype_Prop.make_injs descr sorts) ~~ constr_rep_thms);
haftmann@33968
   564
haftmann@33968
   565
    val ((constr_inject', distinct_thms'), thy6) =
haftmann@33968
   566
      thy5
haftmann@33968
   567
      |> Sign.parent_path
haftmann@33968
   568
      |> store_thmss "inject" new_type_names constr_inject
haftmann@33968
   569
      ||>> store_thmss "distinct" new_type_names distinct_thms;
haftmann@33968
   570
haftmann@33968
   571
    (*************************** induction theorem ****************************)
haftmann@33968
   572
haftmann@33968
   573
    val _ = message config "Proving induction rule for datatypes ...";
haftmann@33968
   574
haftmann@33968
   575
    val Rep_inverse_thms = (map (fn (_, iso, _) => iso RS subst) newT_iso_axms) @
haftmann@33968
   576
      (map (fn r => r RS @{thm the_inv_f_f} RS subst) iso_inj_thms_unfolded);
haftmann@33968
   577
    val Rep_inverse_thms' = map (fn r => r RS @{thm the_inv_f_f}) iso_inj_thms_unfolded;
haftmann@33968
   578
haftmann@33968
   579
    fun mk_indrule_lemma ((i, _), T) (prems, concls) =
haftmann@33968
   580
      let
haftmann@33968
   581
        val Rep_t = Const (nth all_rep_names i, T --> Univ_elT) $
haftmann@33968
   582
          mk_Free "x" T i;
haftmann@33968
   583
haftmann@33968
   584
        val Abs_t = if i < length newTs then
haftmann@33968
   585
            Const (Sign.intern_const thy6
haftmann@33968
   586
              ("Abs_" ^ (nth new_type_names i)), Univ_elT --> T)
haftmann@33968
   587
          else Const (@{const_name the_inv_into},
haftmann@33968
   588
              [HOLogic.mk_setT T, T --> Univ_elT, Univ_elT] ---> T) $
haftmann@33968
   589
            HOLogic.mk_UNIV T $ Const (nth all_rep_names i, T --> Univ_elT)
haftmann@33968
   590
haftmann@33968
   591
      in (prems @ [HOLogic.imp $
haftmann@33968
   592
            (Const (nth rep_set_names i, UnivT') $ Rep_t) $
haftmann@33968
   593
              (mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ (Abs_t $ Rep_t))],
haftmann@33968
   594
          concls @ [mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ mk_Free "x" T i])
haftmann@33968
   595
      end;
haftmann@33968
   596
haftmann@33968
   597
    val (indrule_lemma_prems, indrule_lemma_concls) =
haftmann@33968
   598
      fold mk_indrule_lemma (descr' ~~ recTs) ([], []);
haftmann@33968
   599
haftmann@33968
   600
    val cert = cterm_of thy6;
haftmann@33968
   601
haftmann@33968
   602
    val indrule_lemma = Skip_Proof.prove_global thy6 [] []
haftmann@33968
   603
      (Logic.mk_implies
haftmann@33968
   604
        (HOLogic.mk_Trueprop (mk_conj indrule_lemma_prems),
haftmann@33968
   605
         HOLogic.mk_Trueprop (mk_conj indrule_lemma_concls))) (fn _ => EVERY
haftmann@33968
   606
           [REPEAT (etac conjE 1),
haftmann@33968
   607
            REPEAT (EVERY
haftmann@33968
   608
              [TRY (rtac conjI 1), resolve_tac Rep_inverse_thms 1,
haftmann@33968
   609
               etac mp 1, resolve_tac iso_elem_thms 1])]);
haftmann@33968
   610
haftmann@33968
   611
    val Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule_lemma)));
haftmann@33968
   612
    val frees = if length Ps = 1 then [Free ("P", snd (dest_Var (hd Ps)))] else
haftmann@33968
   613
      map (Free o apfst fst o dest_Var) Ps;
haftmann@33968
   614
    val indrule_lemma' = cterm_instantiate (map cert Ps ~~ map cert frees) indrule_lemma;
haftmann@33968
   615
haftmann@33968
   616
    val dt_induct_prop = Datatype_Prop.make_ind descr sorts;
haftmann@33968
   617
    val dt_induct = Skip_Proof.prove_global thy6 []
haftmann@33968
   618
      (Logic.strip_imp_prems dt_induct_prop) (Logic.strip_imp_concl dt_induct_prop)
haftmann@33968
   619
      (fn {prems, ...} => EVERY
haftmann@33968
   620
        [rtac indrule_lemma' 1,
wenzelm@35625
   621
         (indtac rep_induct [] THEN_ALL_NEW Object_Logic.atomize_prems_tac) 1,
haftmann@33968
   622
         EVERY (map (fn (prem, r) => (EVERY
haftmann@33968
   623
           [REPEAT (eresolve_tac Abs_inverse_thms 1),
haftmann@33968
   624
            simp_tac (HOL_basic_ss addsimps ((symmetric r)::Rep_inverse_thms')) 1,
haftmann@33968
   625
            DEPTH_SOLVE_1 (ares_tac [prem] 1 ORELSE etac allE 1)]))
haftmann@33968
   626
                (prems ~~ (constr_defs @ (map mk_meta_eq iso_char_thms))))]);
haftmann@33968
   627
haftmann@33968
   628
    val ([dt_induct'], thy7) =
haftmann@33968
   629
      thy6
haftmann@33968
   630
      |> Sign.add_path big_name
haftmann@33968
   631
      |> PureThy.add_thms [((Binding.name "induct", dt_induct), [case_names_induct])]
haftmann@33968
   632
      ||> Sign.parent_path
haftmann@33968
   633
      ||> Theory.checkpoint;
haftmann@33968
   634
haftmann@33968
   635
  in
haftmann@33968
   636
    ((constr_inject', distinct_thms', dt_induct'), thy7)
haftmann@33968
   637
  end;
haftmann@33968
   638
haftmann@33968
   639
haftmann@33968
   640
haftmann@33968
   641
(** definitional introduction of datatypes **)
haftmann@33968
   642
haftmann@33968
   643
fun gen_add_datatype prep_typ config new_type_names dts thy =
haftmann@33968
   644
  let
haftmann@33968
   645
    val _ = Theory.requires thy "Datatype" "datatype definitions";
haftmann@33968
   646
haftmann@33968
   647
    (* this theory is used just for parsing *)
haftmann@33968
   648
    val tmp_thy = thy |>
haftmann@33968
   649
      Theory.copy |>
haftmann@33968
   650
      Sign.add_types (map (fn (tvs, tname, mx, _) =>
haftmann@33968
   651
        (tname, length tvs, mx)) dts);
haftmann@33968
   652
haftmann@33968
   653
    val (tyvars, _, _, _)::_ = dts;
haftmann@33968
   654
    val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
wenzelm@35129
   655
      let val full_tname = Sign.full_name tmp_thy tname
haftmann@33968
   656
      in
haftmann@33968
   657
        (case duplicates (op =) tvs of
haftmann@33968
   658
          [] =>
haftmann@33968
   659
            if eq_set (op =) (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
haftmann@33968
   660
            else error ("Mutually recursive datatypes must have same type parameters")
haftmann@33968
   661
        | dups => error ("Duplicate parameter(s) for datatype " ^ quote (Binding.str_of tname) ^
haftmann@33968
   662
            " : " ^ commas dups))
haftmann@33968
   663
      end) dts);
haftmann@33968
   664
    val dt_names = map fst new_dts;
haftmann@33968
   665
haftmann@33968
   666
    val _ =
haftmann@33968
   667
      (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
haftmann@33968
   668
        [] => ()
haftmann@33968
   669
      | dups => error ("Duplicate datatypes: " ^ commas dups));
haftmann@33968
   670
haftmann@33968
   671
    fun prep_dt_spec (tvs, tname, mx, constrs) tname' (dts', constr_syntax, sorts, i) =
haftmann@33968
   672
      let
haftmann@33968
   673
        fun prep_constr (cname, cargs, mx') (constrs, constr_syntax', sorts') =
haftmann@33968
   674
          let
haftmann@33968
   675
            val (cargs', sorts'') = fold_map (prep_typ tmp_thy) cargs sorts';
haftmann@33968
   676
            val _ =
haftmann@33968
   677
              (case subtract (op =) tvs (fold (curry OldTerm.add_typ_tfree_names) cargs' []) of
haftmann@33968
   678
                [] => ()
wenzelm@35129
   679
              | vs => error ("Extra type variables on rhs: " ^ commas vs));
wenzelm@35129
   680
            val c = Sign.full_name_path tmp_thy tname' cname;
wenzelm@35129
   681
          in
wenzelm@35129
   682
            (constrs @ [(c, map (dtyp_of_typ new_dts) cargs')],
haftmann@33968
   683
              constr_syntax' @ [(cname, mx')], sorts'')
haftmann@33968
   684
          end handle ERROR msg => cat_error msg
wenzelm@36148
   685
           ("The error above occurred in constructor " ^ quote (Binding.str_of cname) ^
haftmann@33968
   686
            " of datatype " ^ quote (Binding.str_of tname));
haftmann@33968
   687
haftmann@33968
   688
        val (constrs', constr_syntax', sorts') =
haftmann@33968
   689
          fold prep_constr constrs ([], [], sorts)
haftmann@33968
   690
      in
haftmann@33968
   691
        case duplicates (op =) (map fst constrs') of
wenzelm@35129
   692
          [] =>
wenzelm@35129
   693
            (dts' @ [(i, (Sign.full_name tmp_thy tname, map DtTFree tvs, constrs'))],
haftmann@33968
   694
              constr_syntax @ [constr_syntax'], sorts', i + 1)
wenzelm@35129
   695
        | dups => error ("Duplicate constructors " ^ commas dups ^
haftmann@33968
   696
             " in datatype " ^ quote (Binding.str_of tname))
haftmann@33968
   697
      end;
haftmann@33968
   698
haftmann@33968
   699
    val (dts', constr_syntax, sorts', i) =
haftmann@33968
   700
      fold2 prep_dt_spec dts new_type_names ([], [], [], 0);
haftmann@33968
   701
    val sorts = sorts' @ map (rpair (Sign.defaultS tmp_thy)) (subtract (op =) (map fst sorts') tyvars);
haftmann@33968
   702
    val dt_info = Datatype_Data.get_all thy;
haftmann@33968
   703
    val (descr, _) = unfold_datatypes tmp_thy dts' sorts dt_info dts' i;
haftmann@33968
   704
    val _ = check_nonempty descr handle (exn as Datatype_Empty s) =>
haftmann@33968
   705
      if #strict config then error ("Nonemptiness check failed for datatype " ^ s)
haftmann@33968
   706
      else raise exn;
haftmann@33968
   707
haftmann@33968
   708
    val _ = message config ("Constructing datatype(s) " ^ commas_quote new_type_names);
haftmann@33968
   709
haftmann@33968
   710
  in
haftmann@33968
   711
    thy
haftmann@33968
   712
    |> representation_proofs config dt_info new_type_names descr sorts
haftmann@33968
   713
        types_syntax constr_syntax (Datatype_Data.mk_case_names_induct (flat descr))
haftmann@33968
   714
    |-> (fn (inject, distinct, induct) => Datatype_Data.derive_datatype_props
haftmann@33968
   715
        config dt_names (SOME new_type_names) descr sorts
haftmann@33968
   716
        induct inject distinct)
haftmann@33968
   717
  end;
haftmann@33968
   718
haftmann@33968
   719
val add_datatype = gen_add_datatype Datatype_Data.cert_typ;
haftmann@33968
   720
val datatype_cmd = snd ooo gen_add_datatype Datatype_Data.read_typ default_config;
haftmann@33968
   721
haftmann@33968
   722
local
haftmann@33968
   723
haftmann@33968
   724
structure P = OuterParse and K = OuterKeyword
haftmann@33968
   725
haftmann@33968
   726
fun prep_datatype_decls args =
haftmann@33968
   727
  let
haftmann@33968
   728
    val names = map
haftmann@33968
   729
      (fn ((((NONE, _), t), _), _) => Binding.name_of t | ((((SOME t, _), _), _), _) => t) args;
haftmann@33968
   730
    val specs = map (fn ((((_, vs), t), mx), cons) =>
haftmann@33968
   731
      (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
haftmann@33968
   732
  in (names, specs) end;
haftmann@33968
   733
haftmann@33968
   734
val parse_datatype_decl =
wenzelm@35351
   735
  (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.binding -- P.opt_mixfix --
haftmann@33968
   736
    (P.$$$ "=" |-- P.enum1 "|" (P.binding -- Scan.repeat P.typ -- P.opt_mixfix)));
haftmann@33968
   737
haftmann@33968
   738
val parse_datatype_decls = P.and_list1 parse_datatype_decl >> prep_datatype_decls;
haftmann@33968
   739
haftmann@33968
   740
in
haftmann@33968
   741
haftmann@33968
   742
val _ =
haftmann@33968
   743
  OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
haftmann@33968
   744
    (parse_datatype_decls >> (fn (names, specs) => Toplevel.theory (datatype_cmd names specs)));
wenzelm@6385
   745
wenzelm@30391
   746
end;
haftmann@33968
   747
haftmann@33968
   748
end;