src/HOL/Tools/Old_Datatype/old_datatype.ML
author wenzelm
Fri Mar 06 15:58:56 2015 +0100 (2015-03-06)
changeset 59621 291934bac95e
parent 59617 b60e65ad13df
child 59859 f9d1442c70f3
permissions -rw-r--r--
Thm.cterm_of and Thm.ctyp_of operate on local context;
blanchet@58112
     1
(*  Title:      HOL/Tools/Old_Datatype/old_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
blanchet@58112
    10
signature OLD_DATATYPE =
wenzelm@6360
    11
sig
blanchet@58114
    12
  include OLD_DATATYPE_COMMON
blanchet@58114
    13
wenzelm@45909
    14
  val distinct_lemma: thm
wenzelm@45839
    15
  type spec_cmd =
blanchet@58114
    16
    (binding * (string * string option) list * mixfix) * (binding * string list * mixfix) list
wenzelm@45839
    17
  val read_specs: spec_cmd list -> theory -> spec list * Proof.context
wenzelm@45839
    18
  val check_specs: spec list -> theory -> spec list * Proof.context
blanchet@58114
    19
  val add_datatype: config -> spec list -> theory -> string list * theory
blanchet@58114
    20
  val add_datatype_cmd: config -> spec_cmd list -> theory -> string list * theory
wenzelm@45839
    21
  val spec_cmd: spec_cmd parser
haftmann@32717
    22
end;
haftmann@32717
    23
blanchet@58112
    24
structure Old_Datatype : OLD_DATATYPE =
haftmann@33963
    25
struct
berghofe@5177
    26
haftmann@33968
    27
(** auxiliary **)
haftmann@33968
    28
wenzelm@45909
    29
val distinct_lemma = @{lemma "f x \<noteq> f y ==> x \<noteq> y" by iprover};
wenzelm@59582
    30
val (_ $ (_ $ (_ $ (distinct_f $ _) $ _))) = hd (Thm.prems_of distinct_lemma);
haftmann@33968
    31
blanchet@58112
    32
fun exh_thm_of (dt_info : Old_Datatype_Aux.info Symtab.table) tname =
haftmann@33968
    33
  #exhaust (the (Symtab.lookup dt_info tname));
haftmann@33968
    34
haftmann@33968
    35
val In0_inject = @{thm In0_inject};
haftmann@33968
    36
val In1_inject = @{thm In1_inject};
haftmann@33968
    37
val Scons_inject = @{thm Scons_inject};
haftmann@33968
    38
val Leaf_inject = @{thm Leaf_inject};
haftmann@33968
    39
val In0_eq = @{thm In0_eq};
haftmann@33968
    40
val In1_eq = @{thm In1_eq};
haftmann@33968
    41
val In0_not_In1 = @{thm In0_not_In1};
haftmann@33968
    42
val In1_not_In0 = @{thm In1_not_In0};
haftmann@33968
    43
val Lim_inject = @{thm Lim_inject};
haftmann@33968
    44
val Inl_inject = @{thm Inl_inject};
haftmann@33968
    45
val Inr_inject = @{thm Inr_inject};
haftmann@33968
    46
val Suml_inject = @{thm Suml_inject};
haftmann@33968
    47
val Sumr_inject = @{thm Sumr_inject};
haftmann@33968
    48
wenzelm@40719
    49
val datatype_injI =
wenzelm@40719
    50
  @{lemma "(!!x. ALL y. f x = f y --> x = y) ==> inj f" by (simp add: inj_on_def)};
haftmann@33968
    51
haftmann@33968
    52
haftmann@33968
    53
(** proof of characteristic theorems **)
haftmann@33968
    54
blanchet@58112
    55
fun representation_proofs (config : Old_Datatype_Aux.config)
blanchet@58112
    56
    (dt_info : Old_Datatype_Aux.info Symtab.table) descr types_syntax constr_syntax case_names_induct
blanchet@58112
    57
    thy =
haftmann@33968
    58
  let
haftmann@33968
    59
    val descr' = flat descr;
wenzelm@45701
    60
    val new_type_names = map (Binding.name_of o fst) types_syntax;
haftmann@33968
    61
    val big_name = space_implode "_" new_type_names;
haftmann@33968
    62
    val thy1 = Sign.add_path big_name thy;
blanchet@55408
    63
    val big_rec_name = "rep_set_" ^ big_name;
haftmann@33968
    64
    val rep_set_names' =
wenzelm@45743
    65
      if length descr' = 1 then [big_rec_name]
wenzelm@45821
    66
      else map (prefix (big_rec_name ^ "_") o string_of_int) (1 upto length descr');
haftmann@33968
    67
    val rep_set_names = map (Sign.full_bname thy1) rep_set_names';
haftmann@33968
    68
blanchet@58112
    69
    val tyvars = map (fn (_, (_, Ts, _)) => map Old_Datatype_Aux.dest_DtTFree Ts) (hd descr);
blanchet@58112
    70
    val leafTs' = Old_Datatype_Aux.get_nonrec_types descr';
blanchet@58112
    71
    val branchTs = Old_Datatype_Aux.get_branching_types descr';
wenzelm@45700
    72
    val branchT =
wenzelm@45700
    73
      if null branchTs then HOLogic.unitT
haftmann@37678
    74
      else Balanced_Tree.make (fn (T, U) => Type (@{type_name Sum_Type.sum}, [T, U])) branchTs;
blanchet@58112
    75
    val arities = remove (op =) 0 (Old_Datatype_Aux.get_arities descr');
haftmann@33968
    76
    val unneeded_vars =
wenzelm@45822
    77
      subtract (op =) (fold Term.add_tfreesT (leafTs' @ branchTs) []) (hd tyvars);
wenzelm@45822
    78
    val leafTs = leafTs' @ map TFree unneeded_vars;
blanchet@58112
    79
    val recTs = Old_Datatype_Aux.get_rec_types descr';
haftmann@33968
    80
    val (newTs, oldTs) = chop (length (hd descr)) recTs;
wenzelm@45700
    81
    val sumT =
wenzelm@45700
    82
      if null leafTs then HOLogic.unitT
haftmann@37678
    83
      else Balanced_Tree.make (fn (T, U) => Type (@{type_name Sum_Type.sum}, [T, U])) leafTs;
blanchet@58112
    84
    val Univ_elT = HOLogic.mk_setT (Type (@{type_name Old_Datatype.node}, [sumT, branchT]));
haftmann@33968
    85
    val UnivT = HOLogic.mk_setT Univ_elT;
haftmann@33968
    86
    val UnivT' = Univ_elT --> HOLogic.boolT;
haftmann@33968
    87
    val Collect = Const (@{const_name Collect}, UnivT' --> UnivT);
haftmann@33968
    88
blanchet@58112
    89
    val In0 = Const (@{const_name Old_Datatype.In0}, Univ_elT --> Univ_elT);
blanchet@58112
    90
    val In1 = Const (@{const_name Old_Datatype.In1}, Univ_elT --> Univ_elT);
blanchet@58112
    91
    val Leaf = Const (@{const_name Old_Datatype.Leaf}, sumT --> Univ_elT);
blanchet@58112
    92
    val Lim = Const (@{const_name Old_Datatype.Lim}, (branchT --> Univ_elT) --> Univ_elT);
haftmann@33968
    93
haftmann@33968
    94
    (* make injections needed for embedding types in leaves *)
haftmann@33968
    95
haftmann@33968
    96
    fun mk_inj T' x =
haftmann@33968
    97
      let
haftmann@33968
    98
        fun mk_inj' T n i =
wenzelm@45700
    99
          if n = 1 then x
wenzelm@45700
   100
          else
wenzelm@45700
   101
            let
wenzelm@45700
   102
              val n2 = n div 2;
wenzelm@45700
   103
              val Type (_, [T1, T2]) = T;
wenzelm@45700
   104
            in
wenzelm@45700
   105
              if i <= n2
wenzelm@45821
   106
              then Const (@{const_name Inl}, T1 --> T) $ mk_inj' T1 n2 i
wenzelm@45821
   107
              else Const (@{const_name Inr}, T2 --> T) $ mk_inj' T2 (n - n2) (i - n2)
wenzelm@45700
   108
            end;
wenzelm@45700
   109
      in mk_inj' sumT (length leafTs) (1 + find_index (fn T'' => T'' = T') leafTs) end;
haftmann@33968
   110
haftmann@33968
   111
    (* make injections for constructors *)
haftmann@33968
   112
haftmann@33968
   113
    fun mk_univ_inj ts = Balanced_Tree.access
haftmann@33968
   114
      {left = fn t => In0 $ t,
haftmann@33968
   115
        right = fn t => In1 $ t,
haftmann@33968
   116
        init =
haftmann@33968
   117
          if ts = [] then Const (@{const_name undefined}, Univ_elT)
blanchet@58112
   118
          else foldr1 (HOLogic.mk_binop @{const_name Old_Datatype.Scons}) ts};
haftmann@33968
   119
haftmann@33968
   120
    (* function spaces *)
haftmann@33968
   121
haftmann@33968
   122
    fun mk_fun_inj T' x =
haftmann@33968
   123
      let
haftmann@33968
   124
        fun mk_inj T n i =
wenzelm@45700
   125
          if n = 1 then x
wenzelm@45700
   126
          else
wenzelm@45700
   127
            let
wenzelm@45700
   128
              val n2 = n div 2;
wenzelm@45700
   129
              val Type (_, [T1, T2]) = T;
wenzelm@45700
   130
              fun mkT U = (U --> Univ_elT) --> T --> Univ_elT;
wenzelm@45700
   131
            in
wenzelm@45878
   132
              if i <= n2 then Const (@{const_name Sum_Type.Suml}, mkT T1) $ mk_inj T1 n2 i
wenzelm@45878
   133
              else Const (@{const_name Sum_Type.Sumr}, mkT T2) $ mk_inj T2 (n - n2) (i - n2)
wenzelm@45700
   134
            end;
wenzelm@45700
   135
      in mk_inj branchT (length branchTs) (1 + find_index (fn T'' => T'' = T') branchTs) end;
haftmann@33968
   136
haftmann@33968
   137
    fun mk_lim t Ts = fold_rev (fn T => fn t => Lim $ mk_fun_inj T (Abs ("x", T, t))) Ts t;
haftmann@33968
   138
haftmann@33968
   139
    (************** generate introduction rules for representing set **********)
haftmann@33968
   140
blanchet@58112
   141
    val _ = Old_Datatype_Aux.message config "Constructing representing sets ...";
haftmann@33968
   142
haftmann@33968
   143
    (* make introduction rule for a single constructor *)
haftmann@33968
   144
haftmann@33968
   145
    fun make_intr s n (i, (_, cargs)) =
haftmann@33968
   146
      let
haftmann@33968
   147
        fun mk_prem dt (j, prems, ts) =
blanchet@58112
   148
          (case Old_Datatype_Aux.strip_dtyp dt of
blanchet@58112
   149
            (dts, Old_Datatype_Aux.DtRec k) =>
haftmann@33968
   150
              let
blanchet@58112
   151
                val Ts = map (Old_Datatype_Aux.typ_of_dtyp descr') dts;
haftmann@33968
   152
                val free_t =
blanchet@58112
   153
                  Old_Datatype_Aux.app_bnds (Old_Datatype_Aux.mk_Free "x" (Ts ---> Univ_elT) j)
blanchet@58112
   154
                    (length Ts)
wenzelm@45700
   155
              in
wenzelm@46218
   156
                (j + 1, Logic.list_all (map (pair "x") Ts,
haftmann@33968
   157
                  HOLogic.mk_Trueprop
haftmann@33968
   158
                    (Free (nth rep_set_names' k, UnivT') $ free_t)) :: prems,
haftmann@33968
   159
                mk_lim free_t Ts :: ts)
haftmann@33968
   160
              end
haftmann@33968
   161
          | _ =>
blanchet@58112
   162
              let val T = Old_Datatype_Aux.typ_of_dtyp descr' dt
blanchet@58112
   163
              in (j + 1, prems, (Leaf $ mk_inj T (Old_Datatype_Aux.mk_Free "x" T j)) :: ts) end);
haftmann@33968
   164
haftmann@33968
   165
        val (_, prems, ts) = fold_rev mk_prem cargs (1, [], []);
wenzelm@45700
   166
        val concl = HOLogic.mk_Trueprop (Free (s, UnivT') $ mk_univ_inj ts n i);
wenzelm@45700
   167
      in Logic.list_implies (prems, concl) end;
haftmann@33968
   168
haftmann@33968
   169
    val intr_ts = maps (fn ((_, (_, _, constrs)), rep_set_name) =>
haftmann@33968
   170
      map (make_intr rep_set_name (length constrs))
wenzelm@45821
   171
        ((1 upto length constrs) ~~ constrs)) (descr' ~~ rep_set_names');
haftmann@33968
   172
haftmann@33968
   173
    val ({raw_induct = rep_induct, intrs = rep_intrs, ...}, thy2) =
haftmann@33968
   174
      thy1
haftmann@33968
   175
      |> Sign.map_naming Name_Space.conceal
haftmann@33968
   176
      |> Inductive.add_inductive_global
haftmann@33968
   177
          {quiet_mode = #quiet config, verbose = false, alt_name = Binding.name big_rec_name,
wenzelm@49170
   178
           coind = false, no_elim = true, no_ind = false, skip_mono = true}
haftmann@33968
   179
          (map (fn s => ((Binding.name s, UnivT'), NoSyn)) rep_set_names') []
haftmann@33968
   180
          (map (fn x => (Attrib.empty_binding, x)) intr_ts) []
wenzelm@52788
   181
      ||> Sign.restore_naming thy1;
haftmann@33968
   182
haftmann@33968
   183
    (********************************* typedef ********************************)
haftmann@33968
   184
wenzelm@45701
   185
    val (typedefs, thy3) = thy2
wenzelm@45701
   186
      |> Sign.parent_path
wenzelm@45701
   187
      |> fold_map
wenzelm@45701
   188
        (fn (((name, mx), tvs), c) =>
blanchet@58239
   189
          Typedef.add_typedef_global false (name, tvs, mx)
haftmann@33968
   190
            (Collect $ Const (c, UnivT')) NONE
wenzelm@59498
   191
            (fn ctxt => rtac exI 1 THEN rtac CollectI 1 THEN
haftmann@33968
   192
              QUIET_BREADTH_FIRST (has_fewer_prems 1)
wenzelm@59498
   193
              (resolve_tac ctxt rep_intrs 1)))
wenzelm@45878
   194
        (types_syntax ~~ tyvars ~~ take (length newTs) rep_set_names)
wenzelm@45701
   195
      ||> Sign.add_path big_name;
haftmann@33968
   196
haftmann@33968
   197
    (*********************** definition of constructors ***********************)
haftmann@33968
   198
wenzelm@45878
   199
    val big_rep_name = big_name ^ "_Rep_";
wenzelm@45701
   200
    val rep_names' = map (fn i => big_rep_name ^ string_of_int i) (1 upto length (flat (tl descr)));
wenzelm@45701
   201
    val all_rep_names =
wenzelm@45879
   202
      map (#Rep_name o #1 o #2) typedefs @
haftmann@33968
   203
      map (Sign.full_bname thy3) rep_names';
haftmann@33968
   204
haftmann@33968
   205
    (* isomorphism declarations *)
haftmann@33968
   206
haftmann@33968
   207
    val iso_decls = map (fn (T, s) => (Binding.name s, T --> Univ_elT, NoSyn))
haftmann@33968
   208
      (oldTs ~~ rep_names');
haftmann@33968
   209
haftmann@33968
   210
    (* constructor definitions *)
haftmann@33968
   211
wenzelm@45889
   212
    fun make_constr_def (typedef: Typedef.info) T n
wenzelm@45879
   213
        ((cname, cargs), (cname', mx)) (thy, defs, eqns, i) =
haftmann@33968
   214
      let
haftmann@33968
   215
        fun constr_arg dt (j, l_args, r_args) =
wenzelm@41423
   216
          let
blanchet@58112
   217
            val T = Old_Datatype_Aux.typ_of_dtyp descr' dt;
blanchet@58112
   218
            val free_t = Old_Datatype_Aux.mk_Free "x" T j;
wenzelm@45700
   219
          in
blanchet@58112
   220
            (case (Old_Datatype_Aux.strip_dtyp dt, strip_type T) of
blanchet@58112
   221
              ((_, Old_Datatype_Aux.DtRec m), (Us, U)) =>
wenzelm@45700
   222
                (j + 1, free_t :: l_args, mk_lim
wenzelm@45700
   223
                  (Const (nth all_rep_names m, U --> Univ_elT) $
blanchet@58112
   224
                    Old_Datatype_Aux.app_bnds free_t (length Us)) Us :: r_args)
wenzelm@45879
   225
            | _ => (j + 1, free_t :: l_args, (Leaf $ mk_inj T free_t) :: r_args))
haftmann@33968
   226
          end;
haftmann@33968
   227
haftmann@33968
   228
        val (_, l_args, r_args) = fold_rev constr_arg cargs (1, [], []);
blanchet@58112
   229
        val constrT = map (Old_Datatype_Aux.typ_of_dtyp descr') cargs ---> T;
wenzelm@45879
   230
        val ({Abs_name, Rep_name, ...}, _) = typedef;
haftmann@33968
   231
        val lhs = list_comb (Const (cname, constrT), l_args);
haftmann@33968
   232
        val rhs = mk_univ_inj r_args n i;
wenzelm@45879
   233
        val def = Logic.mk_equals (lhs, Const (Abs_name, Univ_elT --> T) $ rhs);
wenzelm@46909
   234
        val def_name = Thm.def_name (Long_Name.base_name cname);
wenzelm@45821
   235
        val eqn =
wenzelm@45879
   236
          HOLogic.mk_Trueprop (HOLogic.mk_eq (Const (Rep_name, T --> Univ_elT) $ lhs, rhs));
haftmann@33968
   237
        val ([def_thm], thy') =
haftmann@33968
   238
          thy
wenzelm@56239
   239
          |> Sign.add_consts [(cname', constrT, mx)]
wenzelm@39557
   240
          |> (Global_Theory.add_defs false o map Thm.no_attributes) [(Binding.name def_name, def)];
haftmann@33968
   241
haftmann@33968
   242
      in (thy', defs @ [def_thm], eqns @ [eqn], i + 1) end;
haftmann@33968
   243
haftmann@33968
   244
    (* constructor definitions for datatype *)
haftmann@33968
   245
wenzelm@45879
   246
    fun dt_constr_defs (((((_, (_, _, constrs)), tname), typedef: Typedef.info), T), constr_syntax)
haftmann@33968
   247
        (thy, defs, eqns, rep_congs, dist_lemmas) =
haftmann@33968
   248
      let
wenzelm@59582
   249
        val _ $ (_ $ (cong_f $ _) $ _) = Thm.concl_of arg_cong;
wenzelm@59621
   250
        val rep_const = Thm.global_cterm_of thy (Const (#Rep_name (#1 typedef), T --> Univ_elT));
wenzelm@59621
   251
        val cong' = cterm_instantiate [(Thm.global_cterm_of thy cong_f, rep_const)] arg_cong;
wenzelm@59621
   252
        val dist = cterm_instantiate [(Thm.global_cterm_of thy distinct_f, rep_const)] distinct_lemma;
wenzelm@45700
   253
        val (thy', defs', eqns', _) =
wenzelm@45889
   254
          fold (make_constr_def typedef T (length constrs))
wenzelm@45700
   255
            (constrs ~~ constr_syntax) (Sign.add_path tname thy, defs, [], 1);
haftmann@33968
   256
      in
haftmann@33968
   257
        (Sign.parent_path thy', defs', eqns @ [eqns'],
haftmann@33968
   258
          rep_congs @ [cong'], dist_lemmas @ [dist])
haftmann@33968
   259
      end;
haftmann@33968
   260
haftmann@33968
   261
    val (thy4, constr_defs, constr_rep_eqns, rep_congs, dist_lemmas) =
haftmann@33968
   262
      fold dt_constr_defs
wenzelm@45879
   263
        (hd descr ~~ new_type_names ~~ map #2 typedefs ~~ newTs ~~ constr_syntax)
wenzelm@56239
   264
        (thy3 |> Sign.add_consts iso_decls |> Sign.parent_path, [], [], [], []);
haftmann@33968
   265
haftmann@33968
   266
haftmann@33968
   267
    (*********** isomorphisms for new types (introduced by typedef) ***********)
haftmann@33968
   268
blanchet@58112
   269
    val _ = Old_Datatype_Aux.message config "Proving isomorphism properties ...";
haftmann@33968
   270
wenzelm@54742
   271
    val collect_simp = rewrite_rule (Proof_Context.init_global thy4) [mk_meta_eq mem_Collect_eq];
wenzelm@54742
   272
wenzelm@45879
   273
    val newT_iso_axms = typedefs |> map (fn (_, (_, {Abs_inverse, Rep_inverse, Rep, ...})) =>
wenzelm@45879
   274
      (collect_simp Abs_inverse, Rep_inverse, collect_simp Rep));
haftmann@33968
   275
wenzelm@45879
   276
    val newT_iso_inj_thms = typedefs |> map (fn (_, (_, {Abs_inject, Rep_inject, ...})) =>
wenzelm@45879
   277
      (collect_simp Abs_inject RS iffD1, Rep_inject RS iffD1));
haftmann@33968
   278
haftmann@33968
   279
    (********* isomorphisms between existing types and "unfolded" types *******)
haftmann@33968
   280
haftmann@33968
   281
    (*---------------------------------------------------------------------*)
haftmann@33968
   282
    (* isomorphisms are defined using primrec-combinators:                 *)
haftmann@33968
   283
    (* generate appropriate functions for instantiating primrec-combinator *)
haftmann@33968
   284
    (*                                                                     *)
blanchet@55417
   285
    (*   e.g.  Rep_dt_i = list_rec ... (%h t y. In1 (Scons (Leaf h) y))    *)
haftmann@33968
   286
    (*                                                                     *)
haftmann@33968
   287
    (* also generate characteristic equations for isomorphisms             *)
haftmann@33968
   288
    (*                                                                     *)
blanchet@55417
   289
    (*   e.g.  Rep_dt_i (cons h t) = In1 (Scons (Rep_dt_j h) (Rep_dt_i t)) *)
haftmann@33968
   290
    (*---------------------------------------------------------------------*)
haftmann@33968
   291
haftmann@33968
   292
    fun make_iso_def k ks n (cname, cargs) (fs, eqns, i) =
haftmann@33968
   293
      let
blanchet@58112
   294
        val argTs = map (Old_Datatype_Aux.typ_of_dtyp descr') cargs;
haftmann@33968
   295
        val T = nth recTs k;
wenzelm@45879
   296
        val rep_const = Const (nth all_rep_names k, T --> Univ_elT);
haftmann@33968
   297
        val constr = Const (cname, argTs ---> T);
haftmann@33968
   298
haftmann@33968
   299
        fun process_arg ks' dt (i2, i2', ts, Ts) =
haftmann@33968
   300
          let
blanchet@58112
   301
            val T' = Old_Datatype_Aux.typ_of_dtyp descr' dt;
haftmann@33968
   302
            val (Us, U) = strip_type T'
wenzelm@45700
   303
          in
blanchet@58112
   304
            (case Old_Datatype_Aux.strip_dtyp dt of
blanchet@58112
   305
              (_, Old_Datatype_Aux.DtRec j) =>
wenzelm@45700
   306
                if member (op =) ks' j then
blanchet@58112
   307
                  (i2 + 1, i2' + 1, ts @ [mk_lim (Old_Datatype_Aux.app_bnds
blanchet@58112
   308
                     (Old_Datatype_Aux.mk_Free "y" (Us ---> Univ_elT) i2') (length Us)) Us],
haftmann@33968
   309
                   Ts @ [Us ---> Univ_elT])
haftmann@33968
   310
                else
haftmann@33968
   311
                  (i2 + 1, i2', ts @ [mk_lim
haftmann@33968
   312
                     (Const (nth all_rep_names j, U --> Univ_elT) $
blanchet@58112
   313
                        Old_Datatype_Aux.app_bnds
blanchet@58112
   314
                          (Old_Datatype_Aux.mk_Free "x" T' i2) (length Us)) Us], Ts)
blanchet@58112
   315
            | _ => (i2 + 1, i2', ts @ [Leaf $ mk_inj T' (Old_Datatype_Aux.mk_Free "x" T' i2)], Ts))
haftmann@33968
   316
          end;
haftmann@33968
   317
haftmann@33968
   318
        val (i2, i2', ts, Ts) = fold (process_arg ks) cargs (1, 1, [], []);
blanchet@58112
   319
        val xs = map (uncurry (Old_Datatype_Aux.mk_Free "x")) (argTs ~~ (1 upto (i2 - 1)));
blanchet@58112
   320
        val ys = map (uncurry (Old_Datatype_Aux.mk_Free "y")) (Ts ~~ (1 upto (i2' - 1)));
wenzelm@45878
   321
        val f = fold_rev lambda (xs @ ys) (mk_univ_inj ts n i);
haftmann@33968
   322
haftmann@33968
   323
        val (_, _, ts', _) = fold (process_arg []) cargs (1, 1, [], []);
haftmann@33968
   324
        val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
haftmann@33968
   325
          (rep_const $ list_comb (constr, xs), mk_univ_inj ts' n i))
haftmann@33968
   326
haftmann@33968
   327
      in (fs @ [f], eqns @ [eqn], i + 1) end;
haftmann@33968
   328
haftmann@33968
   329
    (* define isomorphisms for all mutually recursive datatypes in list ds *)
haftmann@33968
   330
haftmann@33968
   331
    fun make_iso_defs ds (thy, char_thms) =
haftmann@33968
   332
      let
haftmann@33968
   333
        val ks = map fst ds;
haftmann@33968
   334
        val (_, (tname, _, _)) = hd ds;
haftmann@33968
   335
        val {rec_rewrites, rec_names, ...} = the (Symtab.lookup dt_info tname);
haftmann@33968
   336
wenzelm@45878
   337
        fun process_dt (k, (_, _, constrs)) (fs, eqns, isos) =
haftmann@33968
   338
          let
wenzelm@45700
   339
            val (fs', eqns', _) = fold (make_iso_def k ks (length constrs)) constrs (fs, eqns, 1);
wenzelm@45700
   340
            val iso = (nth recTs k, nth all_rep_names k);
haftmann@33968
   341
          in (fs', eqns', isos @ [iso]) end;
wenzelm@45700
   342
haftmann@33968
   343
        val (fs, eqns, isos) = fold process_dt ds ([], [], []);
haftmann@33968
   344
        val fTs = map fastype_of fs;
wenzelm@45700
   345
        val defs =
wenzelm@45700
   346
          map (fn (rec_name, (T, iso_name)) =>
wenzelm@46909
   347
            (Binding.name (Thm.def_name (Long_Name.base_name iso_name)),
wenzelm@45700
   348
              Logic.mk_equals (Const (iso_name, T --> Univ_elT),
wenzelm@45700
   349
                list_comb (Const (rec_name, fTs @ [T] ---> Univ_elT), fs)))) (rec_names ~~ isos);
haftmann@33968
   350
        val (def_thms, thy') =
wenzelm@52788
   351
          (Global_Theory.add_defs false o map Thm.no_attributes) defs thy;
haftmann@33968
   352
haftmann@33968
   353
        (* prove characteristic equations *)
haftmann@33968
   354
wenzelm@45878
   355
        val rewrites = def_thms @ map mk_meta_eq rec_rewrites;
wenzelm@45700
   356
        val char_thms' =
wenzelm@51551
   357
          map (fn eqn => Goal.prove_sorry_global thy' [] [] eqn
wenzelm@54742
   358
            (fn {context = ctxt, ...} => EVERY [rewrite_goals_tac ctxt rewrites, rtac refl 1])) eqns;
haftmann@33968
   359
haftmann@33968
   360
      in (thy', char_thms' @ char_thms) end;
haftmann@33968
   361
wenzelm@45700
   362
    val (thy5, iso_char_thms) =
wenzelm@52788
   363
      fold_rev make_iso_defs (tl descr) (Sign.add_path big_name thy4, []);
haftmann@33968
   364
haftmann@33968
   365
    (* prove isomorphism properties *)
haftmann@33968
   366
haftmann@33968
   367
    fun mk_funs_inv thy thm =
haftmann@33968
   368
      let
haftmann@33968
   369
        val prop = Thm.prop_of thm;
haftmann@33968
   370
        val _ $ (_ $ ((S as Const (_, Type (_, [U, _]))) $ _ )) $
haftmann@33968
   371
          (_ $ (_ $ (r $ (a $ _)) $ _)) = Type.legacy_freeze prop;
wenzelm@45738
   372
        val used = Term.add_tfree_names a [];
haftmann@33968
   373
haftmann@33968
   374
        fun mk_thm i =
haftmann@33968
   375
          let
wenzelm@56254
   376
            val Ts = map (TFree o rpair @{sort type}) (Name.variant_list used (replicate i "'t"));
wenzelm@45700
   377
            val f = Free ("f", Ts ---> U);
wenzelm@45700
   378
          in
wenzelm@51551
   379
            Goal.prove_sorry_global thy [] []
wenzelm@45700
   380
              (Logic.mk_implies
wenzelm@45700
   381
                (HOLogic.mk_Trueprop (HOLogic.list_all
blanchet@58112
   382
                   (map (pair "x") Ts, S $ Old_Datatype_Aux.app_bnds f i)),
wenzelm@46219
   383
                 HOLogic.mk_Trueprop (HOLogic.mk_eq (fold_rev (Term.abs o pair "x") Ts
blanchet@58112
   384
                   (r $ (a $ Old_Datatype_Aux.app_bnds f i)), f))))
wenzelm@58963
   385
              (fn {context = ctxt, ...} => EVERY [REPEAT_DETERM_N i (rtac @{thm ext} 1),
wenzelm@58963
   386
                 REPEAT (etac allE 1), rtac thm 1, assume_tac ctxt 1])
haftmann@33968
   387
          end
haftmann@33968
   388
      in map (fn r => r RS subst) (thm :: map mk_thm arities) end;
haftmann@33968
   389
blanchet@55417
   390
    (* prove  inj Rep_dt_i  and  Rep_dt_i x : rep_set_dt_i *)
haftmann@33968
   391
wenzelm@45700
   392
    val fun_congs =
wenzelm@59621
   393
      map (fn T => make_elim (Drule.instantiate' [SOME (Thm.global_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;
wenzelm@45700
   398
        val induct = #induct (the (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);
wenzelm@45700
   404
            val rep_set_name = nth rep_set_names i;
wenzelm@45879
   405
            val concl1 =
wenzelm@45879
   406
              HOLogic.all_const T $ Abs ("y", T, HOLogic.imp $
blanchet@58112
   407
                HOLogic.mk_eq (Rep_t $ Old_Datatype_Aux.mk_Free "x" T i, Rep_t $ Bound 0) $
blanchet@58112
   408
                  HOLogic.mk_eq (Old_Datatype_Aux.mk_Free "x" T i, Bound 0));
blanchet@58112
   409
            val concl2 = Const (rep_set_name, UnivT') $ (Rep_t $ Old_Datatype_Aux.mk_Free "x" T i);
wenzelm@45879
   410
          in (concl1, concl2) end;
haftmann@33968
   411
wenzelm@45879
   412
        val (ind_concl1, ind_concl2) = split_list (map mk_ind_concl ds);
haftmann@33968
   413
haftmann@33968
   414
        val rewrites = map mk_meta_eq iso_char_thms;
wenzelm@45700
   415
        val inj_thms' = map snd newT_iso_inj_thms @ map (fn r => r RS @{thm injD}) inj_thms;
haftmann@33968
   416
wenzelm@45700
   417
        val inj_thm =
wenzelm@51551
   418
          Goal.prove_sorry_global thy5 [] []
blanchet@58112
   419
            (HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj ind_concl1))
wenzelm@51798
   420
            (fn {context = ctxt, ...} => EVERY
blanchet@58112
   421
              [(Old_Datatype_Aux.ind_tac induct [] THEN_ALL_NEW Object_Logic.atomize_prems_tac ctxt) 1,
wenzelm@45700
   422
               REPEAT (EVERY
wenzelm@45700
   423
                 [rtac allI 1, rtac impI 1,
wenzelm@58956
   424
                  Old_Datatype_Aux.exh_tac ctxt (exh_thm_of dt_info) 1,
wenzelm@45700
   425
                  REPEAT (EVERY
wenzelm@51798
   426
                    [hyp_subst_tac ctxt 1,
wenzelm@54742
   427
                     rewrite_goals_tac ctxt rewrites,
wenzelm@59498
   428
                     REPEAT (dresolve_tac ctxt [In0_inject, In1_inject] 1),
wenzelm@59498
   429
                     (eresolve_tac ctxt [In0_not_In1 RS notE, In1_not_In0 RS notE] 1)
wenzelm@45700
   430
                     ORELSE (EVERY
wenzelm@59498
   431
                       [REPEAT (eresolve_tac ctxt (Scons_inject ::
wenzelm@45700
   432
                          map make_elim [Leaf_inject, Inl_inject, Inr_inject]) 1),
wenzelm@58956
   433
                        REPEAT (cong_tac ctxt 1), rtac refl 1,
wenzelm@58963
   434
                        REPEAT (assume_tac ctxt 1 ORELSE (EVERY
wenzelm@55990
   435
                          [REPEAT (rtac @{thm ext} 1),
wenzelm@59498
   436
                           REPEAT (eresolve_tac ctxt (mp :: allE ::
wenzelm@45700
   437
                             map make_elim (Suml_inject :: Sumr_inject ::
wenzelm@45700
   438
                               Lim_inject :: inj_thms') @ fun_congs) 1),
wenzelm@58963
   439
                           assume_tac ctxt 1]))])])])]);
haftmann@33968
   440
blanchet@58112
   441
        val inj_thms'' = map (fn r => r RS datatype_injI) (Old_Datatype_Aux.split_conj_thm inj_thm);
haftmann@33968
   442
wenzelm@45700
   443
        val elem_thm =
wenzelm@51551
   444
          Goal.prove_sorry_global thy5 [] []
blanchet@58112
   445
            (HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj ind_concl2))
wenzelm@54742
   446
            (fn {context = ctxt, ...} =>
wenzelm@54742
   447
              EVERY [
blanchet@58112
   448
                (Old_Datatype_Aux.ind_tac induct [] THEN_ALL_NEW Object_Logic.atomize_prems_tac ctxt) 1,
wenzelm@54742
   449
                rewrite_goals_tac ctxt rewrites,
wenzelm@59498
   450
                REPEAT ((resolve_tac ctxt rep_intrs THEN_ALL_NEW
wenzelm@45700
   451
                  ((REPEAT o etac allE) THEN' ares_tac elem_thms)) 1)]);
haftmann@33968
   452
blanchet@58112
   453
      in (inj_thms'' @ inj_thms, elem_thms @ Old_Datatype_Aux.split_conj_thm elem_thm) 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);
wenzelm@45700
   457
    val iso_inj_thms =
wenzelm@45700
   458
      map snd newT_iso_inj_thms @ map (fn r => r RS @{thm injD}) iso_inj_thms_unfolded;
haftmann@33968
   459
blanchet@55417
   460
    (* prove  rep_set_dt_i x --> x : range Rep_dt_i *)
haftmann@33968
   461
haftmann@33968
   462
    fun mk_iso_t (((set_name, iso_name), i), T) =
wenzelm@45700
   463
      let val isoT = T --> Univ_elT in
wenzelm@45700
   464
        HOLogic.imp $
blanchet@58112
   465
          (Const (set_name, UnivT') $ Old_Datatype_Aux.mk_Free "x" Univ_elT i) $
wenzelm@45740
   466
            (if i < length newTs then @{term True}
blanchet@58112
   467
             else HOLogic.mk_mem (Old_Datatype_Aux.mk_Free "x" Univ_elT i,
wenzelm@45700
   468
               Const (@{const_name image}, isoT --> HOLogic.mk_setT T --> UnivT) $
wenzelm@45700
   469
                 Const (iso_name, isoT) $ Const (@{const_abbrev UNIV}, HOLogic.mk_setT T)))
haftmann@33968
   470
      end;
haftmann@33968
   471
blanchet@58112
   472
    val iso_t = HOLogic.mk_Trueprop (Old_Datatype_Aux.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
wenzelm@45700
   477
    val range_eqs = map (fn r => mk_meta_eq (r RS @{thm range_ex1_eq})) iso_inj_thms_unfolded;
haftmann@33968
   478
wenzelm@45700
   479
    val iso_thms =
wenzelm@45700
   480
      if length descr = 1 then []
wenzelm@45700
   481
      else
blanchet@58112
   482
        drop (length newTs) (Old_Datatype_Aux.split_conj_thm
wenzelm@51798
   483
          (Goal.prove_sorry_global thy5 [] [] iso_t (fn {context = ctxt, ...} => EVERY
blanchet@58112
   484
             [(Old_Datatype_Aux.ind_tac rep_induct [] THEN_ALL_NEW
blanchet@58112
   485
                 Object_Logic.atomize_prems_tac ctxt) 1,
wenzelm@45700
   486
              REPEAT (rtac TrueI 1),
wenzelm@54742
   487
              rewrite_goals_tac ctxt (mk_meta_eq @{thm choice_eq} ::
wenzelm@45700
   488
                Thm.symmetric (mk_meta_eq @{thm fun_eq_iff}) :: range_eqs),
wenzelm@54742
   489
              rewrite_goals_tac ctxt (map Thm.symmetric range_eqs),
wenzelm@45700
   490
              REPEAT (EVERY
wenzelm@59498
   491
                [REPEAT (eresolve_tac ctxt ([rangeE, @{thm ex1_implies_ex} RS exE] @
wenzelm@45700
   492
                   maps (mk_funs_inv thy5 o #1) newT_iso_axms) 1),
wenzelm@51798
   493
                 TRY (hyp_subst_tac ctxt 1),
wenzelm@45700
   494
                 rtac (sym RS range_eqI) 1,
wenzelm@59498
   495
                 resolve_tac ctxt iso_char_thms 1])])));
haftmann@33968
   496
haftmann@33968
   497
    val Abs_inverse_thms' =
haftmann@33968
   498
      map #1 newT_iso_axms @
haftmann@33968
   499
      map2 (fn r_inj => fn r => @{thm f_the_inv_into_f} OF [r_inj, r RS mp])
haftmann@33968
   500
        iso_inj_thms_unfolded iso_thms;
haftmann@33968
   501
haftmann@33968
   502
    val Abs_inverse_thms = maps (mk_funs_inv thy5) Abs_inverse_thms';
haftmann@33968
   503
haftmann@33968
   504
    (******************* freeness theorems for constructors *******************)
haftmann@33968
   505
blanchet@58112
   506
    val _ = Old_Datatype_Aux.message config "Proving freeness of constructors ...";
haftmann@33968
   507
haftmann@33968
   508
    (* prove theorem  Rep_i (Constr_j ...) = Inj_j ...  *)
wenzelm@45700
   509
haftmann@33968
   510
    fun prove_constr_rep_thm eqn =
haftmann@33968
   511
      let
haftmann@33968
   512
        val inj_thms = map fst newT_iso_inj_thms;
wenzelm@45878
   513
        val rewrites = @{thm o_def} :: constr_defs @ map (mk_meta_eq o #2) newT_iso_axms;
wenzelm@45700
   514
      in
wenzelm@51551
   515
        Goal.prove_sorry_global thy5 [] [] eqn
wenzelm@54742
   516
        (fn {context = ctxt, ...} => EVERY
wenzelm@59498
   517
          [resolve_tac ctxt inj_thms 1,
wenzelm@54742
   518
           rewrite_goals_tac ctxt rewrites,
wenzelm@45700
   519
           rtac refl 3,
wenzelm@59498
   520
           resolve_tac ctxt rep_intrs 2,
wenzelm@59498
   521
           REPEAT (resolve_tac ctxt iso_elem_thms 1)])
haftmann@33968
   522
      end;
haftmann@33968
   523
haftmann@33968
   524
    (*--------------------------------------------------------------*)
haftmann@33968
   525
    (* constr_rep_thms and rep_congs are used to prove distinctness *)
haftmann@33968
   526
    (* of constructors.                                             *)
haftmann@33968
   527
    (*--------------------------------------------------------------*)
haftmann@33968
   528
haftmann@33968
   529
    val constr_rep_thms = map (map prove_constr_rep_thm) constr_rep_eqns;
haftmann@33968
   530
wenzelm@45700
   531
    val dist_rewrites =
wenzelm@45700
   532
      map (fn (rep_thms, dist_lemma) =>
wenzelm@45878
   533
        dist_lemma :: (rep_thms @ [In0_eq, In1_eq, In0_not_In1, In1_not_In0]))
wenzelm@45700
   534
          (constr_rep_thms ~~ dist_lemmas);
haftmann@33968
   535
wenzelm@45889
   536
    fun prove_distinct_thms dist_rewrites' =
haftmann@33968
   537
      let
haftmann@33968
   538
        fun prove [] = []
haftmann@33968
   539
          | prove (t :: ts) =
haftmann@33968
   540
              let
wenzelm@51717
   541
                val dist_thm = Goal.prove_sorry_global thy5 [] [] t (fn {context = ctxt, ...} =>
wenzelm@51717
   542
                  EVERY [simp_tac (put_simpset HOL_ss ctxt addsimps dist_rewrites') 1])
wenzelm@45910
   543
              in dist_thm :: Drule.zero_var_indexes (dist_thm RS not_sym) :: prove ts end;
wenzelm@45889
   544
      in prove end;
haftmann@33968
   545
wenzelm@45700
   546
    val distinct_thms =
blanchet@58112
   547
      map2 (prove_distinct_thms) dist_rewrites (Old_Datatype_Prop.make_distincts descr);
haftmann@33968
   548
haftmann@33968
   549
    (* prove injectivity of constructors *)
haftmann@33968
   550
haftmann@33968
   551
    fun prove_constr_inj_thm rep_thms t =
wenzelm@45700
   552
      let
wenzelm@45700
   553
        val inj_thms = Scons_inject ::
wenzelm@45700
   554
          map make_elim
wenzelm@45700
   555
            (iso_inj_thms @
wenzelm@45700
   556
              [In0_inject, In1_inject, Leaf_inject, Inl_inject, Inr_inject,
wenzelm@45700
   557
               Lim_inject, Suml_inject, Sumr_inject])
wenzelm@45700
   558
      in
wenzelm@51551
   559
        Goal.prove_sorry_global thy5 [] [] t
wenzelm@51798
   560
          (fn {context = ctxt, ...} => EVERY
wenzelm@45700
   561
            [rtac iffI 1,
wenzelm@51798
   562
             REPEAT (etac conjE 2), hyp_subst_tac ctxt 2, rtac refl 2,
wenzelm@59498
   563
             dresolve_tac ctxt rep_congs 1, dtac @{thm box_equals} 1,
wenzelm@59498
   564
             REPEAT (resolve_tac ctxt rep_thms 1),
wenzelm@59498
   565
             REPEAT (eresolve_tac ctxt inj_thms 1),
wenzelm@55990
   566
             REPEAT (ares_tac [conjI] 1 ORELSE (EVERY [REPEAT (rtac @{thm ext} 1),
wenzelm@59498
   567
               REPEAT (eresolve_tac ctxt (make_elim fun_cong :: inj_thms) 1),
wenzelm@58963
   568
               assume_tac ctxt 1]))])
haftmann@33968
   569
      end;
haftmann@33968
   570
wenzelm@45700
   571
    val constr_inject =
wenzelm@45700
   572
      map (fn (ts, thms) => map (prove_constr_inj_thm thms) ts)
blanchet@58112
   573
        (Old_Datatype_Prop.make_injs descr ~~ constr_rep_thms);
haftmann@33968
   574
haftmann@33968
   575
    val ((constr_inject', distinct_thms'), thy6) =
haftmann@33968
   576
      thy5
haftmann@33968
   577
      |> Sign.parent_path
blanchet@58112
   578
      |> Old_Datatype_Aux.store_thmss "inject" new_type_names constr_inject
blanchet@58112
   579
      ||>> Old_Datatype_Aux.store_thmss "distinct" new_type_names distinct_thms;
haftmann@33968
   580
haftmann@33968
   581
    (*************************** induction theorem ****************************)
haftmann@33968
   582
blanchet@58112
   583
    val _ = Old_Datatype_Aux.message config "Proving induction rule for datatypes ...";
haftmann@33968
   584
wenzelm@45700
   585
    val Rep_inverse_thms =
wenzelm@45700
   586
      map (fn (_, iso, _) => iso RS subst) newT_iso_axms @
wenzelm@45700
   587
      map (fn r => r RS @{thm the_inv_f_f} RS subst) iso_inj_thms_unfolded;
haftmann@33968
   588
    val Rep_inverse_thms' = map (fn r => r RS @{thm the_inv_f_f}) iso_inj_thms_unfolded;
haftmann@33968
   589
wenzelm@45879
   590
    fun mk_indrule_lemma (i, _) T =
haftmann@33968
   591
      let
blanchet@58112
   592
        val Rep_t = Const (nth all_rep_names i, T --> Univ_elT) $ Old_Datatype_Aux.mk_Free "x" T i;
wenzelm@45700
   593
        val Abs_t =
wenzelm@45700
   594
          if i < length newTs then
wenzelm@45879
   595
            Const (#Abs_name (#1 (#2 (nth typedefs i))), Univ_elT --> T)
wenzelm@45879
   596
          else
wenzelm@45879
   597
            Const (@{const_name the_inv_into},
haftmann@33968
   598
              [HOLogic.mk_setT T, T --> Univ_elT, Univ_elT] ---> T) $
wenzelm@45700
   599
            HOLogic.mk_UNIV T $ Const (nth all_rep_names i, T --> Univ_elT);
wenzelm@45879
   600
        val prem =
wenzelm@45879
   601
          HOLogic.imp $
haftmann@33968
   602
            (Const (nth rep_set_names i, UnivT') $ Rep_t) $
blanchet@58112
   603
              (Old_Datatype_Aux.mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ (Abs_t $ Rep_t));
wenzelm@45879
   604
        val concl =
blanchet@58112
   605
          Old_Datatype_Aux.mk_Free "P" (T --> HOLogic.boolT) (i + 1) $
blanchet@58112
   606
            Old_Datatype_Aux.mk_Free "x" T i;
wenzelm@45879
   607
      in (prem, concl) end;
haftmann@33968
   608
haftmann@33968
   609
    val (indrule_lemma_prems, indrule_lemma_concls) =
wenzelm@45879
   610
      split_list (map2 mk_indrule_lemma descr' recTs);
haftmann@33968
   611
wenzelm@45700
   612
    val indrule_lemma =
wenzelm@51551
   613
      Goal.prove_sorry_global thy6 [] []
wenzelm@45700
   614
        (Logic.mk_implies
blanchet@58112
   615
          (HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj indrule_lemma_prems),
blanchet@58112
   616
           HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj indrule_lemma_concls)))
wenzelm@59498
   617
        (fn {context = ctxt, ...} =>
wenzelm@45700
   618
          EVERY
haftmann@33968
   619
           [REPEAT (etac conjE 1),
haftmann@33968
   620
            REPEAT (EVERY
wenzelm@59498
   621
              [TRY (rtac conjI 1), resolve_tac ctxt Rep_inverse_thms 1,
wenzelm@59498
   622
               etac mp 1, resolve_tac ctxt iso_elem_thms 1])]);
haftmann@33968
   623
wenzelm@59582
   624
    val Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of indrule_lemma)));
wenzelm@45700
   625
    val frees =
wenzelm@45700
   626
      if length Ps = 1 then [Free ("P", snd (dest_Var (hd Ps)))]
wenzelm@45700
   627
      else map (Free o apfst fst o dest_Var) Ps;
wenzelm@59617
   628
    val indrule_lemma' =
wenzelm@59621
   629
      cterm_instantiate (map (Thm.global_cterm_of thy6) Ps ~~ map (Thm.global_cterm_of thy6) frees) indrule_lemma;
haftmann@33968
   630
blanchet@58112
   631
    val dt_induct_prop = Old_Datatype_Prop.make_ind descr;
wenzelm@45700
   632
    val dt_induct =
wenzelm@51551
   633
      Goal.prove_sorry_global thy6 []
wenzelm@45700
   634
      (Logic.strip_imp_prems dt_induct_prop)
wenzelm@45700
   635
      (Logic.strip_imp_concl dt_induct_prop)
wenzelm@51717
   636
      (fn {context = ctxt, prems, ...} =>
wenzelm@45700
   637
        EVERY
wenzelm@45700
   638
          [rtac indrule_lemma' 1,
blanchet@58112
   639
           (Old_Datatype_Aux.ind_tac rep_induct [] THEN_ALL_NEW
blanchet@58112
   640
              Object_Logic.atomize_prems_tac ctxt) 1,
wenzelm@45700
   641
           EVERY (map (fn (prem, r) => (EVERY
wenzelm@59498
   642
             [REPEAT (eresolve_tac ctxt Abs_inverse_thms 1),
wenzelm@51717
   643
              simp_tac (put_simpset HOL_basic_ss ctxt
wenzelm@51717
   644
                addsimps (Thm.symmetric r :: Rep_inverse_thms')) 1,
wenzelm@45700
   645
              DEPTH_SOLVE_1 (ares_tac [prem] 1 ORELSE etac allE 1)]))
wenzelm@45878
   646
                  (prems ~~ (constr_defs @ map mk_meta_eq iso_char_thms)))]);
haftmann@33968
   647
wenzelm@45901
   648
    val ([(_, [dt_induct'])], thy7) =
haftmann@33968
   649
      thy6
wenzelm@45901
   650
      |> Global_Theory.note_thmss ""
wenzelm@45901
   651
        [((Binding.qualify true big_name (Binding.name "induct"), [case_names_induct]),
wenzelm@52788
   652
          [([dt_induct], [])])];
haftmann@33968
   653
  in
haftmann@33968
   654
    ((constr_inject', distinct_thms', dt_induct'), thy7)
haftmann@33968
   655
  end;
haftmann@33968
   656
haftmann@33968
   657
haftmann@33968
   658
wenzelm@45701
   659
(** datatype definition **)
haftmann@33968
   660
wenzelm@45839
   661
(* specifications *)
wenzelm@45839
   662
wenzelm@45839
   663
type spec_cmd =
wenzelm@45839
   664
  (binding * (string * string option) list * mixfix) * (binding * string list * mixfix) list;
wenzelm@45839
   665
wenzelm@45839
   666
local
wenzelm@45839
   667
wenzelm@45839
   668
fun parse_spec ctxt ((b, args, mx), constrs) =
wenzelm@45839
   669
  ((b, map (apsnd (Typedecl.read_constraint ctxt)) args, mx),
wenzelm@45839
   670
    constrs |> map (fn (c, Ts, mx') => (c, map (Syntax.parse_typ ctxt) Ts, mx')));
wenzelm@45839
   671
blanchet@58114
   672
fun check_specs ctxt (specs: Old_Datatype_Aux.spec list) =
wenzelm@45839
   673
  let
wenzelm@45839
   674
    fun prep_spec ((tname, args, mx), constrs) tys =
wenzelm@45839
   675
      let
wenzelm@45839
   676
        val (args', tys1) = chop (length args) tys;
wenzelm@45839
   677
        val (constrs', tys3) = (constrs, tys1) |-> fold_map (fn (cname, cargs, mx') => fn tys2 =>
wenzelm@45839
   678
          let val (cargs', tys3) = chop (length cargs) tys2;
wenzelm@45839
   679
          in ((cname, cargs', mx'), tys3) end);
wenzelm@45839
   680
      in (((tname, map dest_TFree args', mx), constrs'), tys3) end;
wenzelm@45839
   681
wenzelm@45839
   682
    val all_tys =
wenzelm@45839
   683
      specs |> maps (fn ((_, args, _), cs) => map TFree args @ maps #2 cs)
wenzelm@45839
   684
      |> Syntax.check_typs ctxt;
wenzelm@45839
   685
wenzelm@45839
   686
  in #1 (fold_map prep_spec specs all_tys) end;
wenzelm@45839
   687
wenzelm@45839
   688
fun prep_specs parse raw_specs thy =
wenzelm@45839
   689
  let
wenzelm@45839
   690
    val ctxt = thy
wenzelm@45839
   691
      |> Sign.add_types_global (map (fn ((b, args, mx), _) => (b, length args, mx)) raw_specs)
wenzelm@45839
   692
      |> Proof_Context.init_global
wenzelm@45839
   693
      |> fold (fn ((_, args, _), _) => fold (fn (a, _) =>
wenzelm@45839
   694
          Variable.declare_typ (TFree (a, dummyS))) args) raw_specs;
wenzelm@45839
   695
    val specs = check_specs ctxt (map (parse ctxt) raw_specs);
wenzelm@45839
   696
  in (specs, ctxt) end;
wenzelm@45839
   697
wenzelm@45839
   698
in
wenzelm@45839
   699
wenzelm@45839
   700
val read_specs = prep_specs parse_spec;
wenzelm@45839
   701
val check_specs = prep_specs (K I);
wenzelm@45839
   702
wenzelm@45839
   703
end;
wenzelm@45839
   704
wenzelm@45839
   705
wenzelm@45839
   706
(* main commands *)
wenzelm@45839
   707
wenzelm@45839
   708
fun gen_add_datatype prep_specs config raw_specs thy =
haftmann@33968
   709
  let
wenzelm@45839
   710
    val (dts, spec_ctxt) = prep_specs raw_specs thy;
wenzelm@45839
   711
    val ((_, tyvars, _), _) :: _ = dts;
wenzelm@45839
   712
    val string_of_tyvar = Syntax.string_of_typ spec_ctxt o TFree;
haftmann@33968
   713
wenzelm@45839
   714
    val (new_dts, types_syntax) = dts |> map (fn ((tname, tvs, mx), _) =>
wenzelm@45839
   715
      let val full_tname = Sign.full_name thy tname in
haftmann@33968
   716
        (case duplicates (op =) tvs of
haftmann@33968
   717
          [] =>
haftmann@33968
   718
            if eq_set (op =) (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
wenzelm@45839
   719
            else error "Mutually recursive datatypes must have same type parameters"
wenzelm@45700
   720
        | dups =>
wenzelm@45700
   721
            error ("Duplicate parameter(s) for datatype " ^ Binding.print tname ^
wenzelm@45839
   722
              " : " ^ commas (map string_of_tyvar dups)))
wenzelm@45839
   723
      end) |> split_list;
haftmann@33968
   724
    val dt_names = map fst new_dts;
haftmann@33968
   725
haftmann@33968
   726
    val _ =
wenzelm@45701
   727
      (case duplicates (op =) (map fst new_dts) of
haftmann@33968
   728
        [] => ()
wenzelm@45822
   729
      | dups => error ("Duplicate datatypes: " ^ commas_quote dups));
haftmann@33968
   730
wenzelm@45889
   731
    fun prep_dt_spec ((tname, tvs, _), constrs) (dts', constr_syntax, i) =
haftmann@33968
   732
      let
wenzelm@45889
   733
        fun prep_constr (cname, cargs, mx) (constrs, constr_syntax') =
haftmann@33968
   734
          let
haftmann@33968
   735
            val _ =
wenzelm@45839
   736
              (case subtract (op =) tvs (fold Term.add_tfreesT cargs []) of
haftmann@33968
   737
                [] => ()
wenzelm@45839
   738
              | vs => error ("Extra type variables on rhs: " ^ commas (map string_of_tyvar vs)));
wenzelm@45839
   739
            val c = Sign.full_name_path thy (Binding.name_of tname) cname;
wenzelm@35129
   740
          in
blanchet@58112
   741
            (constrs @ [(c, map (Old_Datatype_Aux.dtyp_of_typ new_dts) cargs)],
wenzelm@45889
   742
              constr_syntax' @ [(cname, mx)])
wenzelm@45700
   743
          end handle ERROR msg =>
wenzelm@45700
   744
            cat_error msg ("The error above occurred in constructor " ^ Binding.print cname ^
wenzelm@45700
   745
              " of datatype " ^ Binding.print tname);
haftmann@33968
   746
wenzelm@45839
   747
        val (constrs', constr_syntax') = fold prep_constr constrs ([], []);
haftmann@33968
   748
      in
wenzelm@45700
   749
        (case duplicates (op =) (map fst constrs') of
wenzelm@35129
   750
          [] =>
blanchet@58112
   751
            (dts' @ [(i, (Sign.full_name thy tname, map Old_Datatype_Aux.DtTFree tvs, constrs'))],
wenzelm@45839
   752
              constr_syntax @ [constr_syntax'], i + 1)
wenzelm@42381
   753
        | dups =>
wenzelm@45822
   754
            error ("Duplicate constructors " ^ commas_quote dups ^
wenzelm@45822
   755
              " in datatype " ^ Binding.print tname))
haftmann@33968
   756
      end;
haftmann@33968
   757
wenzelm@45839
   758
    val (dts', constr_syntax, i) = fold prep_dt_spec dts ([], [], 0);
wenzelm@45822
   759
blanchet@58112
   760
    val dt_info = Old_Datatype_Data.get_all thy;
blanchet@58112
   761
    val (descr, _) = Old_Datatype_Aux.unfold_datatypes spec_ctxt dts' dt_info dts' i;
wenzelm@41423
   762
    val _ =
blanchet@58112
   763
      Old_Datatype_Aux.check_nonempty descr
blanchet@58112
   764
        handle (exn as Old_Datatype_Aux.Datatype_Empty s) =>
wenzelm@45822
   765
          if #strict config then error ("Nonemptiness check failed for datatype " ^ quote s)
wenzelm@41423
   766
          else reraise exn;
haftmann@33968
   767
wenzelm@45701
   768
    val _ =
blanchet@58112
   769
      Old_Datatype_Aux.message config
wenzelm@45839
   770
        ("Constructing datatype(s) " ^ commas_quote (map (Binding.name_of o #1 o #1) dts));
haftmann@33968
   771
  in
haftmann@33968
   772
    thy
wenzelm@45822
   773
    |> representation_proofs config dt_info descr types_syntax constr_syntax
blanchet@58112
   774
      (Old_Datatype_Data.mk_case_names_induct (flat descr))
wenzelm@45700
   775
    |-> (fn (inject, distinct, induct) =>
blanchet@58112
   776
      Old_Rep_Datatype.derive_datatype_props config dt_names descr induct inject distinct)
haftmann@33968
   777
  end;
haftmann@33968
   778
wenzelm@45839
   779
val add_datatype = gen_add_datatype check_specs;
wenzelm@45863
   780
val add_datatype_cmd = gen_add_datatype read_specs;
haftmann@33968
   781
wenzelm@45701
   782
wenzelm@45839
   783
(* outer syntax *)
haftmann@33968
   784
wenzelm@45839
   785
val spec_cmd =
wenzelm@45839
   786
  Parse.type_args_constrained -- Parse.binding -- Parse.opt_mixfix --
wenzelm@46949
   787
  (@{keyword "="} |-- Parse.enum1 "|" (Parse.binding -- Scan.repeat Parse.typ -- Parse.opt_mixfix))
wenzelm@45839
   788
  >> (fn (((vs, t), mx), cons) => ((t, vs, mx), map Parse.triple1 cons));
haftmann@33968
   789
haftmann@33968
   790
val _ =
blanchet@58305
   791
  Outer_Syntax.command @{command_spec "old_datatype"} "define old-style inductive datatypes"
wenzelm@45863
   792
    (Parse.and_list1 spec_cmd
blanchet@58112
   793
      >> (Toplevel.theory o (snd oo add_datatype_cmd Old_Datatype_Aux.default_config)));
wenzelm@41423
   794
blanchet@58114
   795
open Old_Datatype_Aux;
blanchet@58114
   796
haftmann@33968
   797
end;