src/HOL/Tools/Datatype/datatype.ML
author haftmann
Mon Nov 30 11:42:49 2009 +0100 (2009-11-30)
changeset 33968 f94fb13ecbb3
parent 33963 977b94b64905
child 33969 1e7ca47c6c3d
permissions -rw-r--r--
modernized structures and tuned headers of datatype package modules; joined former datatype.ML and datatype_rep_proofs.ML
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 Numb_name = @{const_name "Datatype.Numb"};
haftmann@33968
    40
val Lim_name = @{const_name "Datatype.Lim"};
haftmann@33968
    41
val Suml_name = @{const_name "Sum_Type.Suml"};
haftmann@33968
    42
val Sumr_name = @{const_name "Sum_Type.Sumr"};
haftmann@33968
    43
haftmann@33968
    44
val In0_inject = @{thm In0_inject};
haftmann@33968
    45
val In1_inject = @{thm In1_inject};
haftmann@33968
    46
val Scons_inject = @{thm Scons_inject};
haftmann@33968
    47
val Leaf_inject = @{thm Leaf_inject};
haftmann@33968
    48
val In0_eq = @{thm In0_eq};
haftmann@33968
    49
val In1_eq = @{thm In1_eq};
haftmann@33968
    50
val In0_not_In1 = @{thm In0_not_In1};
haftmann@33968
    51
val In1_not_In0 = @{thm In1_not_In0};
haftmann@33968
    52
val Lim_inject = @{thm Lim_inject};
haftmann@33968
    53
val Inl_inject = @{thm Inl_inject};
haftmann@33968
    54
val Inr_inject = @{thm Inr_inject};
haftmann@33968
    55
val Suml_inject = @{thm Suml_inject};
haftmann@33968
    56
val Sumr_inject = @{thm Sumr_inject};
haftmann@33968
    57
haftmann@33968
    58
haftmann@33968
    59
haftmann@33968
    60
(** proof of characteristic theorems **)
haftmann@33968
    61
haftmann@33968
    62
fun representation_proofs (config : config) (dt_info : info Symtab.table)
haftmann@33968
    63
      new_type_names descr sorts types_syntax constr_syntax case_names_induct thy =
haftmann@33968
    64
  let
haftmann@33968
    65
    val descr' = flat descr;
haftmann@33968
    66
    val big_name = space_implode "_" new_type_names;
haftmann@33968
    67
    val thy1 = Sign.add_path big_name thy;
haftmann@33968
    68
    val big_rec_name = big_name ^ "_rep_set";
haftmann@33968
    69
    val rep_set_names' =
haftmann@33968
    70
      (if length descr' = 1 then [big_rec_name] else
haftmann@33968
    71
        (map ((curry (op ^) (big_rec_name ^ "_")) o string_of_int)
haftmann@33968
    72
          (1 upto (length descr'))));
haftmann@33968
    73
    val rep_set_names = map (Sign.full_bname thy1) rep_set_names';
haftmann@33968
    74
haftmann@33968
    75
    val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
haftmann@33968
    76
    val leafTs' = get_nonrec_types descr' sorts;
haftmann@33968
    77
    val branchTs = get_branching_types descr' sorts;
haftmann@33968
    78
    val branchT = if null branchTs then HOLogic.unitT
haftmann@33968
    79
      else Balanced_Tree.make (fn (T, U) => Type ("+", [T, U])) branchTs;
haftmann@33968
    80
    val arities = remove (op =) 0 (get_arities descr');
haftmann@33968
    81
    val unneeded_vars =
haftmann@33968
    82
      subtract (op =) (List.foldr OldTerm.add_typ_tfree_names [] (leafTs' @ branchTs)) (hd tyvars);
haftmann@33968
    83
    val leafTs = leafTs' @ map (fn n => TFree (n, (the o AList.lookup (op =) sorts) n)) unneeded_vars;
haftmann@33968
    84
    val recTs = get_rec_types descr' sorts;
haftmann@33968
    85
    val (newTs, oldTs) = chop (length (hd descr)) recTs;
haftmann@33968
    86
    val sumT = if null leafTs then HOLogic.unitT
haftmann@33968
    87
      else Balanced_Tree.make (fn (T, U) => Type ("+", [T, U])) leafTs;
haftmann@33968
    88
    val Univ_elT = HOLogic.mk_setT (Type (node_name, [sumT, branchT]));
haftmann@33968
    89
    val UnivT = HOLogic.mk_setT Univ_elT;
haftmann@33968
    90
    val UnivT' = Univ_elT --> HOLogic.boolT;
haftmann@33968
    91
    val Collect = Const (@{const_name Collect}, UnivT' --> UnivT);
haftmann@33968
    92
haftmann@33968
    93
    val In0 = Const (In0_name, Univ_elT --> Univ_elT);
haftmann@33968
    94
    val In1 = Const (In1_name, Univ_elT --> Univ_elT);
haftmann@33968
    95
    val Leaf = Const (Leaf_name, sumT --> Univ_elT);
haftmann@33968
    96
    val Lim = Const (Lim_name, (branchT --> Univ_elT) --> Univ_elT);
haftmann@33968
    97
haftmann@33968
    98
    (* make injections needed for embedding types in leaves *)
haftmann@33968
    99
haftmann@33968
   100
    fun mk_inj T' x =
haftmann@33968
   101
      let
haftmann@33968
   102
        fun mk_inj' T n i =
haftmann@33968
   103
          if n = 1 then x else
haftmann@33968
   104
          let val n2 = n div 2;
haftmann@33968
   105
              val Type (_, [T1, T2]) = T
haftmann@33968
   106
          in
haftmann@33968
   107
            if i <= n2 then
haftmann@33968
   108
              Const (@{const_name "Sum_Type.Inl"}, T1 --> T) $ (mk_inj' T1 n2 i)
haftmann@33968
   109
            else
haftmann@33968
   110
              Const (@{const_name "Sum_Type.Inr"}, T2 --> T) $ (mk_inj' T2 (n - n2) (i - n2))
haftmann@33968
   111
          end
haftmann@33968
   112
      in mk_inj' sumT (length leafTs) (1 + find_index (fn T'' => T'' = T') leafTs)
haftmann@33968
   113
      end;
haftmann@33968
   114
haftmann@33968
   115
    (* make injections for constructors *)
haftmann@33968
   116
haftmann@33968
   117
    fun mk_univ_inj ts = Balanced_Tree.access
haftmann@33968
   118
      {left = fn t => In0 $ t,
haftmann@33968
   119
        right = fn t => In1 $ t,
haftmann@33968
   120
        init =
haftmann@33968
   121
          if ts = [] then Const (@{const_name undefined}, Univ_elT)
haftmann@33968
   122
          else foldr1 (HOLogic.mk_binop Scons_name) ts};
haftmann@33968
   123
haftmann@33968
   124
    (* function spaces *)
haftmann@33968
   125
haftmann@33968
   126
    fun mk_fun_inj T' x =
haftmann@33968
   127
      let
haftmann@33968
   128
        fun mk_inj T n i =
haftmann@33968
   129
          if n = 1 then x else
haftmann@33968
   130
          let
haftmann@33968
   131
            val n2 = n div 2;
haftmann@33968
   132
            val Type (_, [T1, T2]) = T;
haftmann@33968
   133
            fun mkT U = (U --> Univ_elT) --> T --> Univ_elT
haftmann@33968
   134
          in
haftmann@33968
   135
            if i <= n2 then Const (Suml_name, mkT T1) $ mk_inj T1 n2 i
haftmann@33968
   136
            else Const (Sumr_name, mkT T2) $ mk_inj T2 (n - n2) (i - n2)
haftmann@33968
   137
          end
haftmann@33968
   138
      in mk_inj branchT (length branchTs) (1 + find_index (fn T'' => T'' = T') branchTs)
haftmann@33968
   139
      end;
haftmann@33968
   140
haftmann@33968
   141
    fun mk_lim t Ts = fold_rev (fn T => fn t => Lim $ mk_fun_inj T (Abs ("x", T, t))) Ts t;
haftmann@33968
   142
haftmann@33968
   143
    (************** generate introduction rules for representing set **********)
haftmann@33968
   144
haftmann@33968
   145
    val _ = message config "Constructing representing sets ...";
haftmann@33968
   146
haftmann@33968
   147
    (* make introduction rule for a single constructor *)
haftmann@33968
   148
haftmann@33968
   149
    fun make_intr s n (i, (_, cargs)) =
haftmann@33968
   150
      let
haftmann@33968
   151
        fun mk_prem dt (j, prems, ts) =
haftmann@33968
   152
          (case strip_dtyp dt of
haftmann@33968
   153
            (dts, DtRec k) =>
haftmann@33968
   154
              let
haftmann@33968
   155
                val Ts = map (typ_of_dtyp descr' sorts) dts;
haftmann@33968
   156
                val free_t =
haftmann@33968
   157
                  app_bnds (mk_Free "x" (Ts ---> Univ_elT) j) (length Ts)
haftmann@33968
   158
              in (j + 1, list_all (map (pair "x") Ts,
haftmann@33968
   159
                  HOLogic.mk_Trueprop
haftmann@33968
   160
                    (Free (nth rep_set_names' k, UnivT') $ free_t)) :: prems,
haftmann@33968
   161
                mk_lim free_t Ts :: ts)
haftmann@33968
   162
              end
haftmann@33968
   163
          | _ =>
haftmann@33968
   164
              let val T = typ_of_dtyp descr' sorts dt
haftmann@33968
   165
              in (j + 1, prems, (Leaf $ mk_inj T (mk_Free "x" T j))::ts)
haftmann@33968
   166
              end);
haftmann@33968
   167
haftmann@33968
   168
        val (_, prems, ts) = fold_rev mk_prem cargs (1, [], []);
haftmann@33968
   169
        val concl = HOLogic.mk_Trueprop
haftmann@33968
   170
          (Free (s, UnivT') $ mk_univ_inj ts n i)
haftmann@33968
   171
      in Logic.list_implies (prems, concl)
haftmann@33968
   172
      end;
haftmann@33968
   173
haftmann@33968
   174
    val intr_ts = maps (fn ((_, (_, _, constrs)), rep_set_name) =>
haftmann@33968
   175
      map (make_intr rep_set_name (length constrs))
haftmann@33968
   176
        ((1 upto (length constrs)) ~~ constrs)) (descr' ~~ rep_set_names');
haftmann@33968
   177
haftmann@33968
   178
    val ({raw_induct = rep_induct, intrs = rep_intrs, ...}, thy2) =
haftmann@33968
   179
      thy1
haftmann@33968
   180
      |> Sign.map_naming Name_Space.conceal
haftmann@33968
   181
      |> Inductive.add_inductive_global
haftmann@33968
   182
          {quiet_mode = #quiet config, verbose = false, alt_name = Binding.name big_rec_name,
haftmann@33968
   183
           coind = false, no_elim = true, no_ind = false, skip_mono = true, fork_mono = false}
haftmann@33968
   184
          (map (fn s => ((Binding.name s, UnivT'), NoSyn)) rep_set_names') []
haftmann@33968
   185
          (map (fn x => (Attrib.empty_binding, x)) intr_ts) []
haftmann@33968
   186
      ||> Sign.restore_naming thy1
haftmann@33968
   187
      ||> Theory.checkpoint;
haftmann@33968
   188
haftmann@33968
   189
    (********************************* typedef ********************************)
haftmann@33968
   190
haftmann@33968
   191
    val (typedefs, thy3) = thy2 |>
haftmann@33968
   192
      Sign.parent_path |>
haftmann@33968
   193
      fold_map (fn ((((name, mx), tvs), c), name') =>
haftmann@33968
   194
          Typedef.add_typedef false (SOME (Binding.name name')) (name, 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' =
haftmann@33968
   257
          Drule.standard (cterm_instantiate [(cterm_of thy cong_f, rep_const)] arg_cong);
haftmann@33968
   258
        val dist =
haftmann@33968
   259
          Drule.standard (cterm_instantiate [(cterm_of thy distinct_f, rep_const)] distinct_lemma);
haftmann@33968
   260
        val (thy', defs', eqns', _) = fold ((make_constr_def tname T) (length constrs))
haftmann@33968
   261
          (constrs ~~ constr_syntax) (Sign.add_path tname thy, defs, [], 1);
haftmann@33968
   262
      in
haftmann@33968
   263
        (Sign.parent_path thy', defs', eqns @ [eqns'],
haftmann@33968
   264
          rep_congs @ [cong'], dist_lemmas @ [dist])
haftmann@33968
   265
      end;
haftmann@33968
   266
haftmann@33968
   267
    val (thy4, constr_defs, constr_rep_eqns, rep_congs, dist_lemmas) =
haftmann@33968
   268
      fold dt_constr_defs
haftmann@33968
   269
        (hd descr ~~ new_type_names ~~ newTs ~~ constr_syntax)
haftmann@33968
   270
        (thy3 |> Sign.add_consts_i iso_decls |> Sign.parent_path, [], [], [], []);
haftmann@33968
   271
haftmann@33968
   272
haftmann@33968
   273
    (*********** isomorphisms for new types (introduced by typedef) ***********)
haftmann@33968
   274
haftmann@33968
   275
    val _ = message config "Proving isomorphism properties ...";
haftmann@33968
   276
haftmann@33968
   277
    val newT_iso_axms = map (fn (_, td) =>
haftmann@33968
   278
      (collect_simp (#Abs_inverse td), #Rep_inverse td,
haftmann@33968
   279
       collect_simp (#Rep td))) typedefs;
haftmann@33968
   280
haftmann@33968
   281
    val newT_iso_inj_thms = map (fn (_, td) =>
haftmann@33968
   282
      (collect_simp (#Abs_inject td) RS iffD1, #Rep_inject td RS iffD1)) typedefs;
haftmann@33968
   283
haftmann@33968
   284
    (********* isomorphisms between existing types and "unfolded" types *******)
haftmann@33968
   285
haftmann@33968
   286
    (*---------------------------------------------------------------------*)
haftmann@33968
   287
    (* isomorphisms are defined using primrec-combinators:                 *)
haftmann@33968
   288
    (* generate appropriate functions for instantiating primrec-combinator *)
haftmann@33968
   289
    (*                                                                     *)
haftmann@33968
   290
    (*   e.g.  dt_Rep_i = list_rec ... (%h t y. In1 (Scons (Leaf h) y))    *)
haftmann@33968
   291
    (*                                                                     *)
haftmann@33968
   292
    (* also generate characteristic equations for isomorphisms             *)
haftmann@33968
   293
    (*                                                                     *)
haftmann@33968
   294
    (*   e.g.  dt_Rep_i (cons h t) = In1 (Scons (dt_Rep_j h) (dt_Rep_i t)) *)
haftmann@33968
   295
    (*---------------------------------------------------------------------*)
haftmann@33968
   296
haftmann@33968
   297
    fun make_iso_def k ks n (cname, cargs) (fs, eqns, i) =
haftmann@33968
   298
      let
haftmann@33968
   299
        val argTs = map (typ_of_dtyp descr' sorts) cargs;
haftmann@33968
   300
        val T = nth recTs k;
haftmann@33968
   301
        val rep_name = nth all_rep_names k;
haftmann@33968
   302
        val rep_const = Const (rep_name, T --> Univ_elT);
haftmann@33968
   303
        val constr = Const (cname, argTs ---> T);
haftmann@33968
   304
haftmann@33968
   305
        fun process_arg ks' dt (i2, i2', ts, Ts) =
haftmann@33968
   306
          let
haftmann@33968
   307
            val T' = typ_of_dtyp descr' sorts dt;
haftmann@33968
   308
            val (Us, U) = strip_type T'
haftmann@33968
   309
          in (case strip_dtyp dt of
haftmann@33968
   310
              (_, DtRec j) => if j mem ks' then
haftmann@33968
   311
                  (i2 + 1, i2' + 1, ts @ [mk_lim (app_bnds
haftmann@33968
   312
                     (mk_Free "y" (Us ---> Univ_elT) i2') (length Us)) Us],
haftmann@33968
   313
                   Ts @ [Us ---> Univ_elT])
haftmann@33968
   314
                else
haftmann@33968
   315
                  (i2 + 1, i2', ts @ [mk_lim
haftmann@33968
   316
                     (Const (nth all_rep_names j, U --> Univ_elT) $
haftmann@33968
   317
                        app_bnds (mk_Free "x" T' i2) (length Us)) Us], Ts)
haftmann@33968
   318
            | _ => (i2 + 1, i2', ts @ [Leaf $ mk_inj T' (mk_Free "x" T' i2)], Ts))
haftmann@33968
   319
          end;
haftmann@33968
   320
haftmann@33968
   321
        val (i2, i2', ts, Ts) = fold (process_arg ks) cargs (1, 1, [], []);
haftmann@33968
   322
        val xs = map (uncurry (mk_Free "x")) (argTs ~~ (1 upto (i2 - 1)));
haftmann@33968
   323
        val ys = map (uncurry (mk_Free "y")) (Ts ~~ (1 upto (i2' - 1)));
haftmann@33968
   324
        val f = list_abs_free (map dest_Free (xs @ ys), mk_univ_inj ts n i);
haftmann@33968
   325
haftmann@33968
   326
        val (_, _, ts', _) = fold (process_arg []) cargs (1, 1, [], []);
haftmann@33968
   327
        val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
haftmann@33968
   328
          (rep_const $ list_comb (constr, xs), mk_univ_inj ts' n i))
haftmann@33968
   329
haftmann@33968
   330
      in (fs @ [f], eqns @ [eqn], i + 1) end;
haftmann@33968
   331
haftmann@33968
   332
    (* define isomorphisms for all mutually recursive datatypes in list ds *)
haftmann@33968
   333
haftmann@33968
   334
    fun make_iso_defs ds (thy, char_thms) =
haftmann@33968
   335
      let
haftmann@33968
   336
        val ks = map fst ds;
haftmann@33968
   337
        val (_, (tname, _, _)) = hd ds;
haftmann@33968
   338
        val {rec_rewrites, rec_names, ...} = the (Symtab.lookup dt_info tname);
haftmann@33968
   339
haftmann@33968
   340
        fun process_dt (k, (tname, _, constrs)) (fs, eqns, isos) =
haftmann@33968
   341
          let
haftmann@33968
   342
            val (fs', eqns', _) =
haftmann@33968
   343
              fold (make_iso_def k ks (length constrs)) constrs (fs, eqns, 1);
haftmann@33968
   344
            val iso = (nth recTs k, nth all_rep_names k)
haftmann@33968
   345
          in (fs', eqns', isos @ [iso]) end;
haftmann@33968
   346
        
haftmann@33968
   347
        val (fs, eqns, isos) = fold process_dt ds ([], [], []);
haftmann@33968
   348
        val fTs = map fastype_of fs;
haftmann@33968
   349
        val defs = map (fn (rec_name, (T, iso_name)) => (Binding.name (Long_Name.base_name iso_name ^ "_def"),
haftmann@33968
   350
          Logic.mk_equals (Const (iso_name, T --> Univ_elT),
haftmann@33968
   351
            list_comb (Const (rec_name, fTs @ [T] ---> Univ_elT), fs)))) (rec_names ~~ isos);
haftmann@33968
   352
        val (def_thms, thy') =
haftmann@33968
   353
          apsnd Theory.checkpoint ((PureThy.add_defs false o map Thm.no_attributes) defs thy);
haftmann@33968
   354
haftmann@33968
   355
        (* prove characteristic equations *)
haftmann@33968
   356
haftmann@33968
   357
        val rewrites = def_thms @ (map mk_meta_eq rec_rewrites);
haftmann@33968
   358
        val char_thms' = map (fn eqn => Skip_Proof.prove_global thy' [] [] eqn
haftmann@33968
   359
          (fn _ => EVERY [rewrite_goals_tac rewrites, rtac refl 1])) eqns;
haftmann@33968
   360
haftmann@33968
   361
      in (thy', char_thms' @ char_thms) end;
haftmann@33968
   362
haftmann@33968
   363
    val (thy5, iso_char_thms) = apfst Theory.checkpoint (fold_rev make_iso_defs
haftmann@33968
   364
        (tl descr) (Sign.add_path big_name thy4, []));
haftmann@33968
   365
haftmann@33968
   366
    (* prove isomorphism properties *)
haftmann@33968
   367
haftmann@33968
   368
    fun mk_funs_inv thy thm =
haftmann@33968
   369
      let
haftmann@33968
   370
        val prop = Thm.prop_of thm;
haftmann@33968
   371
        val _ $ (_ $ ((S as Const (_, Type (_, [U, _]))) $ _ )) $
haftmann@33968
   372
          (_ $ (_ $ (r $ (a $ _)) $ _)) = Type.legacy_freeze prop;
haftmann@33968
   373
        val used = OldTerm.add_term_tfree_names (a, []);
haftmann@33968
   374
haftmann@33968
   375
        fun mk_thm i =
haftmann@33968
   376
          let
haftmann@33968
   377
            val Ts = map (TFree o rpair HOLogic.typeS)
haftmann@33968
   378
              (Name.variant_list used (replicate i "'t"));
haftmann@33968
   379
            val f = Free ("f", Ts ---> U)
haftmann@33968
   380
          in Skip_Proof.prove_global thy [] [] (Logic.mk_implies
haftmann@33968
   381
            (HOLogic.mk_Trueprop (HOLogic.list_all
haftmann@33968
   382
               (map (pair "x") Ts, S $ app_bnds f i)),
haftmann@33968
   383
             HOLogic.mk_Trueprop (HOLogic.mk_eq (list_abs (map (pair "x") Ts,
haftmann@33968
   384
               r $ (a $ app_bnds f i)), f))))
haftmann@33968
   385
            (fn _ => EVERY [REPEAT_DETERM_N i (rtac ext 1),
haftmann@33968
   386
               REPEAT (etac allE 1), rtac thm 1, atac 1])
haftmann@33968
   387
          end
haftmann@33968
   388
      in map (fn r => r RS subst) (thm :: map mk_thm arities) end;
haftmann@33968
   389
haftmann@33968
   390
    (* prove  inj dt_Rep_i  and  dt_Rep_i x : dt_rep_set_i *)
haftmann@33968
   391
haftmann@33968
   392
    val fun_congs = map (fn T => make_elim (Drule.instantiate'
haftmann@33968
   393
      [SOME (ctyp_of thy5 T)] [] fun_cong)) branchTs;
haftmann@33968
   394
haftmann@33968
   395
    fun prove_iso_thms ds (inj_thms, elem_thms) =
haftmann@33968
   396
      let
haftmann@33968
   397
        val (_, (tname, _, _)) = hd ds;
haftmann@33968
   398
        val induct = (#induct o the o Symtab.lookup dt_info) tname;
haftmann@33968
   399
haftmann@33968
   400
        fun mk_ind_concl (i, _) =
haftmann@33968
   401
          let
haftmann@33968
   402
            val T = nth recTs i;
haftmann@33968
   403
            val Rep_t = Const (nth all_rep_names i, T --> Univ_elT);
haftmann@33968
   404
            val rep_set_name = nth rep_set_names i
haftmann@33968
   405
          in (HOLogic.all_const T $ Abs ("y", T, HOLogic.imp $
haftmann@33968
   406
                HOLogic.mk_eq (Rep_t $ mk_Free "x" T i, Rep_t $ Bound 0) $
haftmann@33968
   407
                  HOLogic.mk_eq (mk_Free "x" T i, Bound 0)),
haftmann@33968
   408
              Const (rep_set_name, UnivT') $ (Rep_t $ mk_Free "x" T i))
haftmann@33968
   409
          end;
haftmann@33968
   410
haftmann@33968
   411
        val (ind_concl1, ind_concl2) = ListPair.unzip (map mk_ind_concl ds);
haftmann@33968
   412
haftmann@33968
   413
        val rewrites = map mk_meta_eq iso_char_thms;
haftmann@33968
   414
        val inj_thms' = map snd newT_iso_inj_thms @
haftmann@33968
   415
          map (fn r => r RS @{thm injD}) inj_thms;
haftmann@33968
   416
haftmann@33968
   417
        val inj_thm = Skip_Proof.prove_global thy5 [] []
haftmann@33968
   418
          (HOLogic.mk_Trueprop (mk_conj ind_concl1)) (fn _ => EVERY
haftmann@33968
   419
            [(indtac induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
haftmann@33968
   420
             REPEAT (EVERY
haftmann@33968
   421
               [rtac allI 1, rtac impI 1,
haftmann@33968
   422
                exh_tac (exh_thm_of dt_info) 1,
haftmann@33968
   423
                REPEAT (EVERY
haftmann@33968
   424
                  [hyp_subst_tac 1,
haftmann@33968
   425
                   rewrite_goals_tac rewrites,
haftmann@33968
   426
                   REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
haftmann@33968
   427
                   (eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1)
haftmann@33968
   428
                   ORELSE (EVERY
haftmann@33968
   429
                     [REPEAT (eresolve_tac (Scons_inject ::
haftmann@33968
   430
                        map make_elim [Leaf_inject, Inl_inject, Inr_inject]) 1),
haftmann@33968
   431
                      REPEAT (cong_tac 1), rtac refl 1,
haftmann@33968
   432
                      REPEAT (atac 1 ORELSE (EVERY
haftmann@33968
   433
                        [REPEAT (rtac ext 1),
haftmann@33968
   434
                         REPEAT (eresolve_tac (mp :: allE ::
haftmann@33968
   435
                           map make_elim (Suml_inject :: Sumr_inject ::
haftmann@33968
   436
                             Lim_inject :: inj_thms') @ fun_congs) 1),
haftmann@33968
   437
                         atac 1]))])])])]);
haftmann@33968
   438
haftmann@33968
   439
        val inj_thms'' = map (fn r => r RS @{thm datatype_injI})
haftmann@33968
   440
                             (split_conj_thm inj_thm);
haftmann@33968
   441
haftmann@33968
   442
        val elem_thm = 
haftmann@33968
   443
            Skip_Proof.prove_global thy5 [] [] (HOLogic.mk_Trueprop (mk_conj ind_concl2))
haftmann@33968
   444
              (fn _ =>
haftmann@33968
   445
               EVERY [(indtac induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
haftmann@33968
   446
                rewrite_goals_tac rewrites,
haftmann@33968
   447
                REPEAT ((resolve_tac rep_intrs THEN_ALL_NEW
haftmann@33968
   448
                  ((REPEAT o etac allE) THEN' ares_tac elem_thms)) 1)]);
haftmann@33968
   449
haftmann@33968
   450
      in (inj_thms'' @ inj_thms, elem_thms @ (split_conj_thm elem_thm))
haftmann@33968
   451
      end;
haftmann@33968
   452
haftmann@33968
   453
    val (iso_inj_thms_unfolded, iso_elem_thms) =
haftmann@33968
   454
      fold_rev prove_iso_thms (tl descr) ([], map #3 newT_iso_axms);
haftmann@33968
   455
    val iso_inj_thms = map snd newT_iso_inj_thms @
haftmann@33968
   456
      map (fn r => r RS @{thm injD}) iso_inj_thms_unfolded;
haftmann@33968
   457
haftmann@33968
   458
    (* prove  dt_rep_set_i x --> x : range dt_Rep_i *)
haftmann@33968
   459
haftmann@33968
   460
    fun mk_iso_t (((set_name, iso_name), i), T) =
haftmann@33968
   461
      let val isoT = T --> Univ_elT
haftmann@33968
   462
      in HOLogic.imp $ 
haftmann@33968
   463
        (Const (set_name, UnivT') $ mk_Free "x" Univ_elT i) $
haftmann@33968
   464
          (if i < length newTs then HOLogic.true_const
haftmann@33968
   465
           else HOLogic.mk_mem (mk_Free "x" Univ_elT i,
haftmann@33968
   466
             Const (@{const_name image}, isoT --> HOLogic.mk_setT T --> UnivT) $
haftmann@33968
   467
               Const (iso_name, isoT) $ Const (@{const_name UNIV}, HOLogic.mk_setT T)))
haftmann@33968
   468
      end;
haftmann@33968
   469
haftmann@33968
   470
    val iso_t = HOLogic.mk_Trueprop (mk_conj (map mk_iso_t
haftmann@33968
   471
      (rep_set_names ~~ all_rep_names ~~ (0 upto (length descr' - 1)) ~~ recTs)));
haftmann@33968
   472
haftmann@33968
   473
    (* all the theorems are proved by one single simultaneous induction *)
haftmann@33968
   474
haftmann@33968
   475
    val range_eqs = map (fn r => mk_meta_eq (r RS @{thm range_ex1_eq}))
haftmann@33968
   476
      iso_inj_thms_unfolded;
haftmann@33968
   477
haftmann@33968
   478
    val iso_thms = if length descr = 1 then [] else
haftmann@33968
   479
      drop (length newTs) (split_conj_thm
haftmann@33968
   480
        (Skip_Proof.prove_global thy5 [] [] iso_t (fn _ => EVERY
haftmann@33968
   481
           [(indtac rep_induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
haftmann@33968
   482
            REPEAT (rtac TrueI 1),
haftmann@33968
   483
            rewrite_goals_tac (mk_meta_eq choice_eq ::
haftmann@33968
   484
              symmetric (mk_meta_eq @{thm expand_fun_eq}) :: range_eqs),
haftmann@33968
   485
            rewrite_goals_tac (map symmetric range_eqs),
haftmann@33968
   486
            REPEAT (EVERY
haftmann@33968
   487
              [REPEAT (eresolve_tac ([rangeE, ex1_implies_ex RS exE] @
haftmann@33968
   488
                 maps (mk_funs_inv thy5 o #1) newT_iso_axms) 1),
haftmann@33968
   489
               TRY (hyp_subst_tac 1),
haftmann@33968
   490
               rtac (sym RS range_eqI) 1,
haftmann@33968
   491
               resolve_tac iso_char_thms 1])])));
haftmann@33968
   492
haftmann@33968
   493
    val Abs_inverse_thms' =
haftmann@33968
   494
      map #1 newT_iso_axms @
haftmann@33968
   495
      map2 (fn r_inj => fn r => @{thm f_the_inv_into_f} OF [r_inj, r RS mp])
haftmann@33968
   496
        iso_inj_thms_unfolded iso_thms;
haftmann@33968
   497
haftmann@33968
   498
    val Abs_inverse_thms = maps (mk_funs_inv thy5) Abs_inverse_thms';
haftmann@33968
   499
haftmann@33968
   500
    (******************* freeness theorems for constructors *******************)
haftmann@33968
   501
haftmann@33968
   502
    val _ = message config "Proving freeness of constructors ...";
haftmann@33968
   503
haftmann@33968
   504
    (* prove theorem  Rep_i (Constr_j ...) = Inj_j ...  *)
haftmann@33968
   505
    
haftmann@33968
   506
    fun prove_constr_rep_thm eqn =
haftmann@33968
   507
      let
haftmann@33968
   508
        val inj_thms = map fst newT_iso_inj_thms;
haftmann@33968
   509
        val rewrites = @{thm o_def} :: constr_defs @ (map (mk_meta_eq o #2) newT_iso_axms)
haftmann@33968
   510
      in Skip_Proof.prove_global thy5 [] [] eqn (fn _ => EVERY
haftmann@33968
   511
        [resolve_tac inj_thms 1,
haftmann@33968
   512
         rewrite_goals_tac rewrites,
haftmann@33968
   513
         rtac refl 3,
haftmann@33968
   514
         resolve_tac rep_intrs 2,
haftmann@33968
   515
         REPEAT (resolve_tac iso_elem_thms 1)])
haftmann@33968
   516
      end;
haftmann@33968
   517
haftmann@33968
   518
    (*--------------------------------------------------------------*)
haftmann@33968
   519
    (* constr_rep_thms and rep_congs are used to prove distinctness *)
haftmann@33968
   520
    (* of constructors.                                             *)
haftmann@33968
   521
    (*--------------------------------------------------------------*)
haftmann@33968
   522
haftmann@33968
   523
    val constr_rep_thms = map (map prove_constr_rep_thm) constr_rep_eqns;
haftmann@33968
   524
haftmann@33968
   525
    val dist_rewrites = map (fn (rep_thms, dist_lemma) =>
haftmann@33968
   526
      dist_lemma::(rep_thms @ [In0_eq, In1_eq, In0_not_In1, In1_not_In0]))
haftmann@33968
   527
        (constr_rep_thms ~~ dist_lemmas);
haftmann@33968
   528
haftmann@33968
   529
    fun prove_distinct_thms dist_rewrites' (k, ts) =
haftmann@33968
   530
      let
haftmann@33968
   531
        fun prove [] = []
haftmann@33968
   532
          | prove (t :: ts) =
haftmann@33968
   533
              let
haftmann@33968
   534
                val dist_thm = Skip_Proof.prove_global thy5 [] [] t (fn _ =>
haftmann@33968
   535
                  EVERY [simp_tac (HOL_ss addsimps dist_rewrites') 1])
haftmann@33968
   536
              in dist_thm :: Drule.standard (dist_thm RS not_sym) :: prove ts end;
haftmann@33968
   537
      in prove ts end;
haftmann@33968
   538
haftmann@33968
   539
    val distinct_thms = map2 (prove_distinct_thms)
haftmann@33968
   540
      dist_rewrites (Datatype_Prop.make_distincts descr sorts);
haftmann@33968
   541
haftmann@33968
   542
    (* prove injectivity of constructors *)
haftmann@33968
   543
haftmann@33968
   544
    fun prove_constr_inj_thm rep_thms t =
haftmann@33968
   545
      let val inj_thms = Scons_inject :: (map make_elim
haftmann@33968
   546
        (iso_inj_thms @
haftmann@33968
   547
          [In0_inject, In1_inject, Leaf_inject, Inl_inject, Inr_inject,
haftmann@33968
   548
           Lim_inject, Suml_inject, Sumr_inject]))
haftmann@33968
   549
      in Skip_Proof.prove_global thy5 [] [] t (fn _ => EVERY
haftmann@33968
   550
        [rtac iffI 1,
haftmann@33968
   551
         REPEAT (etac conjE 2), hyp_subst_tac 2, rtac refl 2,
haftmann@33968
   552
         dresolve_tac rep_congs 1, dtac box_equals 1,
haftmann@33968
   553
         REPEAT (resolve_tac rep_thms 1),
haftmann@33968
   554
         REPEAT (eresolve_tac inj_thms 1),
haftmann@33968
   555
         REPEAT (ares_tac [conjI] 1 ORELSE (EVERY [REPEAT (rtac ext 1),
haftmann@33968
   556
           REPEAT (eresolve_tac (make_elim fun_cong :: inj_thms) 1),
haftmann@33968
   557
           atac 1]))])
haftmann@33968
   558
      end;
haftmann@33968
   559
haftmann@33968
   560
    val constr_inject = map (fn (ts, thms) => map (prove_constr_inj_thm thms) ts)
haftmann@33968
   561
      ((Datatype_Prop.make_injs descr sorts) ~~ constr_rep_thms);
haftmann@33968
   562
haftmann@33968
   563
    val ((constr_inject', distinct_thms'), thy6) =
haftmann@33968
   564
      thy5
haftmann@33968
   565
      |> Sign.parent_path
haftmann@33968
   566
      |> store_thmss "inject" new_type_names constr_inject
haftmann@33968
   567
      ||>> store_thmss "distinct" new_type_names distinct_thms;
haftmann@33968
   568
haftmann@33968
   569
    (*************************** induction theorem ****************************)
haftmann@33968
   570
haftmann@33968
   571
    val _ = message config "Proving induction rule for datatypes ...";
haftmann@33968
   572
haftmann@33968
   573
    val Rep_inverse_thms = (map (fn (_, iso, _) => iso RS subst) newT_iso_axms) @
haftmann@33968
   574
      (map (fn r => r RS @{thm the_inv_f_f} RS subst) iso_inj_thms_unfolded);
haftmann@33968
   575
    val Rep_inverse_thms' = map (fn r => r RS @{thm the_inv_f_f}) iso_inj_thms_unfolded;
haftmann@33968
   576
haftmann@33968
   577
    fun mk_indrule_lemma ((i, _), T) (prems, concls) =
haftmann@33968
   578
      let
haftmann@33968
   579
        val Rep_t = Const (nth all_rep_names i, T --> Univ_elT) $
haftmann@33968
   580
          mk_Free "x" T i;
haftmann@33968
   581
haftmann@33968
   582
        val Abs_t = if i < length newTs then
haftmann@33968
   583
            Const (Sign.intern_const thy6
haftmann@33968
   584
              ("Abs_" ^ (nth new_type_names i)), Univ_elT --> T)
haftmann@33968
   585
          else Const (@{const_name the_inv_into},
haftmann@33968
   586
              [HOLogic.mk_setT T, T --> Univ_elT, Univ_elT] ---> T) $
haftmann@33968
   587
            HOLogic.mk_UNIV T $ Const (nth all_rep_names i, T --> Univ_elT)
haftmann@33968
   588
haftmann@33968
   589
      in (prems @ [HOLogic.imp $
haftmann@33968
   590
            (Const (nth rep_set_names i, UnivT') $ Rep_t) $
haftmann@33968
   591
              (mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ (Abs_t $ Rep_t))],
haftmann@33968
   592
          concls @ [mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ mk_Free "x" T i])
haftmann@33968
   593
      end;
haftmann@33968
   594
haftmann@33968
   595
    val (indrule_lemma_prems, indrule_lemma_concls) =
haftmann@33968
   596
      fold mk_indrule_lemma (descr' ~~ recTs) ([], []);
haftmann@33968
   597
haftmann@33968
   598
    val cert = cterm_of thy6;
haftmann@33968
   599
haftmann@33968
   600
    val indrule_lemma = Skip_Proof.prove_global thy6 [] []
haftmann@33968
   601
      (Logic.mk_implies
haftmann@33968
   602
        (HOLogic.mk_Trueprop (mk_conj indrule_lemma_prems),
haftmann@33968
   603
         HOLogic.mk_Trueprop (mk_conj indrule_lemma_concls))) (fn _ => EVERY
haftmann@33968
   604
           [REPEAT (etac conjE 1),
haftmann@33968
   605
            REPEAT (EVERY
haftmann@33968
   606
              [TRY (rtac conjI 1), resolve_tac Rep_inverse_thms 1,
haftmann@33968
   607
               etac mp 1, resolve_tac iso_elem_thms 1])]);
haftmann@33968
   608
haftmann@33968
   609
    val Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule_lemma)));
haftmann@33968
   610
    val frees = if length Ps = 1 then [Free ("P", snd (dest_Var (hd Ps)))] else
haftmann@33968
   611
      map (Free o apfst fst o dest_Var) Ps;
haftmann@33968
   612
    val indrule_lemma' = cterm_instantiate (map cert Ps ~~ map cert frees) indrule_lemma;
haftmann@33968
   613
haftmann@33968
   614
    val dt_induct_prop = Datatype_Prop.make_ind descr sorts;
haftmann@33968
   615
    val dt_induct = Skip_Proof.prove_global thy6 []
haftmann@33968
   616
      (Logic.strip_imp_prems dt_induct_prop) (Logic.strip_imp_concl dt_induct_prop)
haftmann@33968
   617
      (fn {prems, ...} => EVERY
haftmann@33968
   618
        [rtac indrule_lemma' 1,
haftmann@33968
   619
         (indtac rep_induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
haftmann@33968
   620
         EVERY (map (fn (prem, r) => (EVERY
haftmann@33968
   621
           [REPEAT (eresolve_tac Abs_inverse_thms 1),
haftmann@33968
   622
            simp_tac (HOL_basic_ss addsimps ((symmetric r)::Rep_inverse_thms')) 1,
haftmann@33968
   623
            DEPTH_SOLVE_1 (ares_tac [prem] 1 ORELSE etac allE 1)]))
haftmann@33968
   624
                (prems ~~ (constr_defs @ (map mk_meta_eq iso_char_thms))))]);
haftmann@33968
   625
haftmann@33968
   626
    val ([dt_induct'], thy7) =
haftmann@33968
   627
      thy6
haftmann@33968
   628
      |> Sign.add_path big_name
haftmann@33968
   629
      |> PureThy.add_thms [((Binding.name "induct", dt_induct), [case_names_induct])]
haftmann@33968
   630
      ||> Sign.parent_path
haftmann@33968
   631
      ||> Theory.checkpoint;
haftmann@33968
   632
haftmann@33968
   633
  in
haftmann@33968
   634
    ((constr_inject', distinct_thms', dt_induct'), thy7)
haftmann@33968
   635
  end;
haftmann@33968
   636
haftmann@33968
   637
haftmann@33968
   638
haftmann@33968
   639
(** definitional introduction of datatypes **)
haftmann@33968
   640
haftmann@33968
   641
fun gen_add_datatype prep_typ config new_type_names dts thy =
haftmann@33968
   642
  let
haftmann@33968
   643
    val _ = Theory.requires thy "Datatype" "datatype definitions";
haftmann@33968
   644
haftmann@33968
   645
    (* this theory is used just for parsing *)
haftmann@33968
   646
    val tmp_thy = thy |>
haftmann@33968
   647
      Theory.copy |>
haftmann@33968
   648
      Sign.add_types (map (fn (tvs, tname, mx, _) =>
haftmann@33968
   649
        (tname, length tvs, mx)) dts);
haftmann@33968
   650
haftmann@33968
   651
    val (tyvars, _, _, _)::_ = dts;
haftmann@33968
   652
    val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
haftmann@33968
   653
      let val full_tname = Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname)
haftmann@33968
   654
      in
haftmann@33968
   655
        (case duplicates (op =) tvs of
haftmann@33968
   656
          [] =>
haftmann@33968
   657
            if eq_set (op =) (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
haftmann@33968
   658
            else error ("Mutually recursive datatypes must have same type parameters")
haftmann@33968
   659
        | dups => error ("Duplicate parameter(s) for datatype " ^ quote (Binding.str_of tname) ^
haftmann@33968
   660
            " : " ^ commas dups))
haftmann@33968
   661
      end) dts);
haftmann@33968
   662
    val dt_names = map fst new_dts;
haftmann@33968
   663
haftmann@33968
   664
    val _ =
haftmann@33968
   665
      (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
haftmann@33968
   666
        [] => ()
haftmann@33968
   667
      | dups => error ("Duplicate datatypes: " ^ commas dups));
haftmann@33968
   668
haftmann@33968
   669
    fun prep_dt_spec (tvs, tname, mx, constrs) tname' (dts', constr_syntax, sorts, i) =
haftmann@33968
   670
      let
haftmann@33968
   671
        fun prep_constr (cname, cargs, mx') (constrs, constr_syntax', sorts') =
haftmann@33968
   672
          let
haftmann@33968
   673
            val (cargs', sorts'') = fold_map (prep_typ tmp_thy) cargs sorts';
haftmann@33968
   674
            val _ =
haftmann@33968
   675
              (case subtract (op =) tvs (fold (curry OldTerm.add_typ_tfree_names) cargs' []) of
haftmann@33968
   676
                [] => ()
haftmann@33968
   677
              | vs => error ("Extra type variables on rhs: " ^ commas vs))
haftmann@33968
   678
          in (constrs @ [(Sign.full_name_path tmp_thy tname'
haftmann@33968
   679
                  (Binding.map_name (Syntax.const_name mx') cname),
haftmann@33968
   680
                   map (dtyp_of_typ new_dts) cargs')],
haftmann@33968
   681
              constr_syntax' @ [(cname, mx')], sorts'')
haftmann@33968
   682
          end handle ERROR msg => cat_error msg
haftmann@33968
   683
           ("The error above occured in constructor " ^ quote (Binding.str_of cname) ^
haftmann@33968
   684
            " of datatype " ^ quote (Binding.str_of tname));
haftmann@33968
   685
haftmann@33968
   686
        val (constrs', constr_syntax', sorts') =
haftmann@33968
   687
          fold prep_constr constrs ([], [], sorts)
haftmann@33968
   688
haftmann@33968
   689
      in
haftmann@33968
   690
        case duplicates (op =) (map fst constrs') of
haftmann@33968
   691
           [] =>
haftmann@33968
   692
             (dts' @ [(i, (Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname),
haftmann@33968
   693
                map DtTFree tvs, constrs'))],
haftmann@33968
   694
              constr_syntax @ [constr_syntax'], sorts', i + 1)
haftmann@33968
   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 =
haftmann@33968
   735
  (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.binding -- P.opt_infix --
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;