src/HOL/Tools/Old_Datatype/old_datatype.ML
author wenzelm
Sat Jul 25 23:41:53 2015 +0200 (2015-07-25)
changeset 60781 2da59cdf531c
parent 60774 6c28d8ed2488
child 60801 7664e0916eec
permissions -rw-r--r--
updated to infer_instantiate;
tuned;
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
wenzelm@59880
   175
      |> Sign.concealed
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@60752
   191
            (fn ctxt =>
wenzelm@60752
   192
              resolve_tac ctxt [exI] 1 THEN
wenzelm@60752
   193
              resolve_tac ctxt [CollectI] 1 THEN
haftmann@33968
   194
              QUIET_BREADTH_FIRST (has_fewer_prems 1)
wenzelm@59498
   195
              (resolve_tac ctxt rep_intrs 1)))
wenzelm@45878
   196
        (types_syntax ~~ tyvars ~~ take (length newTs) rep_set_names)
wenzelm@45701
   197
      ||> Sign.add_path big_name;
haftmann@33968
   198
haftmann@33968
   199
    (*********************** definition of constructors ***********************)
haftmann@33968
   200
wenzelm@45878
   201
    val big_rep_name = big_name ^ "_Rep_";
wenzelm@45701
   202
    val rep_names' = map (fn i => big_rep_name ^ string_of_int i) (1 upto length (flat (tl descr)));
wenzelm@45701
   203
    val all_rep_names =
wenzelm@45879
   204
      map (#Rep_name o #1 o #2) typedefs @
haftmann@33968
   205
      map (Sign.full_bname thy3) rep_names';
haftmann@33968
   206
haftmann@33968
   207
    (* isomorphism declarations *)
haftmann@33968
   208
haftmann@33968
   209
    val iso_decls = map (fn (T, s) => (Binding.name s, T --> Univ_elT, NoSyn))
haftmann@33968
   210
      (oldTs ~~ rep_names');
haftmann@33968
   211
haftmann@33968
   212
    (* constructor definitions *)
haftmann@33968
   213
wenzelm@45889
   214
    fun make_constr_def (typedef: Typedef.info) T n
wenzelm@45879
   215
        ((cname, cargs), (cname', mx)) (thy, defs, eqns, i) =
haftmann@33968
   216
      let
haftmann@33968
   217
        fun constr_arg dt (j, l_args, r_args) =
wenzelm@41423
   218
          let
blanchet@58112
   219
            val T = Old_Datatype_Aux.typ_of_dtyp descr' dt;
blanchet@58112
   220
            val free_t = Old_Datatype_Aux.mk_Free "x" T j;
wenzelm@45700
   221
          in
blanchet@58112
   222
            (case (Old_Datatype_Aux.strip_dtyp dt, strip_type T) of
blanchet@58112
   223
              ((_, Old_Datatype_Aux.DtRec m), (Us, U)) =>
wenzelm@45700
   224
                (j + 1, free_t :: l_args, mk_lim
wenzelm@45700
   225
                  (Const (nth all_rep_names m, U --> Univ_elT) $
blanchet@58112
   226
                    Old_Datatype_Aux.app_bnds free_t (length Us)) Us :: r_args)
wenzelm@45879
   227
            | _ => (j + 1, free_t :: l_args, (Leaf $ mk_inj T free_t) :: r_args))
haftmann@33968
   228
          end;
haftmann@33968
   229
haftmann@33968
   230
        val (_, l_args, r_args) = fold_rev constr_arg cargs (1, [], []);
blanchet@58112
   231
        val constrT = map (Old_Datatype_Aux.typ_of_dtyp descr') cargs ---> T;
wenzelm@45879
   232
        val ({Abs_name, Rep_name, ...}, _) = typedef;
haftmann@33968
   233
        val lhs = list_comb (Const (cname, constrT), l_args);
haftmann@33968
   234
        val rhs = mk_univ_inj r_args n i;
wenzelm@45879
   235
        val def = Logic.mk_equals (lhs, Const (Abs_name, Univ_elT --> T) $ rhs);
wenzelm@46909
   236
        val def_name = Thm.def_name (Long_Name.base_name cname);
wenzelm@45821
   237
        val eqn =
wenzelm@45879
   238
          HOLogic.mk_Trueprop (HOLogic.mk_eq (Const (Rep_name, T --> Univ_elT) $ lhs, rhs));
haftmann@33968
   239
        val ([def_thm], thy') =
haftmann@33968
   240
          thy
wenzelm@56239
   241
          |> Sign.add_consts [(cname', constrT, mx)]
wenzelm@39557
   242
          |> (Global_Theory.add_defs false o map Thm.no_attributes) [(Binding.name def_name, def)];
haftmann@33968
   243
haftmann@33968
   244
      in (thy', defs @ [def_thm], eqns @ [eqn], i + 1) end;
haftmann@33968
   245
haftmann@33968
   246
    (* constructor definitions for datatype *)
haftmann@33968
   247
wenzelm@45879
   248
    fun dt_constr_defs (((((_, (_, _, constrs)), tname), typedef: Typedef.info), T), constr_syntax)
haftmann@33968
   249
        (thy, defs, eqns, rep_congs, dist_lemmas) =
haftmann@33968
   250
      let
wenzelm@60781
   251
        val ctxt = Proof_Context.init_global thy;
wenzelm@59582
   252
        val _ $ (_ $ (cong_f $ _) $ _) = Thm.concl_of arg_cong;
wenzelm@60781
   253
        val rep_const = Thm.cterm_of ctxt (Const (#Rep_name (#1 typedef), T --> Univ_elT));
wenzelm@60781
   254
        val cong' = infer_instantiate ctxt [(#1 (dest_Var cong_f), rep_const)] arg_cong;
wenzelm@60781
   255
        val dist = infer_instantiate ctxt [(#1 (dest_Var distinct_f), rep_const)] distinct_lemma;
wenzelm@45700
   256
        val (thy', defs', eqns', _) =
wenzelm@45889
   257
          fold (make_constr_def typedef T (length constrs))
wenzelm@45700
   258
            (constrs ~~ constr_syntax) (Sign.add_path tname thy, defs, [], 1);
haftmann@33968
   259
      in
haftmann@33968
   260
        (Sign.parent_path thy', defs', eqns @ [eqns'],
haftmann@33968
   261
          rep_congs @ [cong'], dist_lemmas @ [dist])
haftmann@33968
   262
      end;
haftmann@33968
   263
haftmann@33968
   264
    val (thy4, constr_defs, constr_rep_eqns, rep_congs, dist_lemmas) =
haftmann@33968
   265
      fold dt_constr_defs
wenzelm@45879
   266
        (hd descr ~~ new_type_names ~~ map #2 typedefs ~~ newTs ~~ constr_syntax)
wenzelm@56239
   267
        (thy3 |> Sign.add_consts iso_decls |> Sign.parent_path, [], [], [], []);
haftmann@33968
   268
haftmann@33968
   269
haftmann@33968
   270
    (*********** isomorphisms for new types (introduced by typedef) ***********)
haftmann@33968
   271
blanchet@58112
   272
    val _ = Old_Datatype_Aux.message config "Proving isomorphism properties ...";
haftmann@33968
   273
wenzelm@54742
   274
    val collect_simp = rewrite_rule (Proof_Context.init_global thy4) [mk_meta_eq mem_Collect_eq];
wenzelm@54742
   275
wenzelm@45879
   276
    val newT_iso_axms = typedefs |> map (fn (_, (_, {Abs_inverse, Rep_inverse, Rep, ...})) =>
wenzelm@45879
   277
      (collect_simp Abs_inverse, Rep_inverse, collect_simp Rep));
haftmann@33968
   278
wenzelm@45879
   279
    val newT_iso_inj_thms = typedefs |> map (fn (_, (_, {Abs_inject, Rep_inject, ...})) =>
wenzelm@45879
   280
      (collect_simp Abs_inject RS iffD1, Rep_inject RS iffD1));
haftmann@33968
   281
haftmann@33968
   282
    (********* isomorphisms between existing types and "unfolded" types *******)
haftmann@33968
   283
haftmann@33968
   284
    (*---------------------------------------------------------------------*)
haftmann@33968
   285
    (* isomorphisms are defined using primrec-combinators:                 *)
haftmann@33968
   286
    (* generate appropriate functions for instantiating primrec-combinator *)
haftmann@33968
   287
    (*                                                                     *)
blanchet@55417
   288
    (*   e.g.  Rep_dt_i = list_rec ... (%h t y. In1 (Scons (Leaf h) y))    *)
haftmann@33968
   289
    (*                                                                     *)
haftmann@33968
   290
    (* also generate characteristic equations for isomorphisms             *)
haftmann@33968
   291
    (*                                                                     *)
blanchet@55417
   292
    (*   e.g.  Rep_dt_i (cons h t) = In1 (Scons (Rep_dt_j h) (Rep_dt_i t)) *)
haftmann@33968
   293
    (*---------------------------------------------------------------------*)
haftmann@33968
   294
haftmann@33968
   295
    fun make_iso_def k ks n (cname, cargs) (fs, eqns, i) =
haftmann@33968
   296
      let
blanchet@58112
   297
        val argTs = map (Old_Datatype_Aux.typ_of_dtyp descr') cargs;
haftmann@33968
   298
        val T = nth recTs k;
wenzelm@45879
   299
        val rep_const = Const (nth all_rep_names k, T --> Univ_elT);
haftmann@33968
   300
        val constr = Const (cname, argTs ---> T);
haftmann@33968
   301
haftmann@33968
   302
        fun process_arg ks' dt (i2, i2', ts, Ts) =
haftmann@33968
   303
          let
blanchet@58112
   304
            val T' = Old_Datatype_Aux.typ_of_dtyp descr' dt;
haftmann@33968
   305
            val (Us, U) = strip_type T'
wenzelm@45700
   306
          in
blanchet@58112
   307
            (case Old_Datatype_Aux.strip_dtyp dt of
blanchet@58112
   308
              (_, Old_Datatype_Aux.DtRec j) =>
wenzelm@45700
   309
                if member (op =) ks' j then
blanchet@58112
   310
                  (i2 + 1, i2' + 1, ts @ [mk_lim (Old_Datatype_Aux.app_bnds
blanchet@58112
   311
                     (Old_Datatype_Aux.mk_Free "y" (Us ---> Univ_elT) i2') (length Us)) Us],
haftmann@33968
   312
                   Ts @ [Us ---> Univ_elT])
haftmann@33968
   313
                else
haftmann@33968
   314
                  (i2 + 1, i2', ts @ [mk_lim
haftmann@33968
   315
                     (Const (nth all_rep_names j, U --> Univ_elT) $
blanchet@58112
   316
                        Old_Datatype_Aux.app_bnds
blanchet@58112
   317
                          (Old_Datatype_Aux.mk_Free "x" T' i2) (length Us)) Us], Ts)
blanchet@58112
   318
            | _ => (i2 + 1, i2', ts @ [Leaf $ mk_inj T' (Old_Datatype_Aux.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, [], []);
blanchet@58112
   322
        val xs = map (uncurry (Old_Datatype_Aux.mk_Free "x")) (argTs ~~ (1 upto (i2 - 1)));
blanchet@58112
   323
        val ys = map (uncurry (Old_Datatype_Aux.mk_Free "y")) (Ts ~~ (1 upto (i2' - 1)));
wenzelm@45878
   324
        val f = fold_rev lambda (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
wenzelm@45878
   340
        fun process_dt (k, (_, _, constrs)) (fs, eqns, isos) =
haftmann@33968
   341
          let
wenzelm@45700
   342
            val (fs', eqns', _) = fold (make_iso_def k ks (length constrs)) constrs (fs, eqns, 1);
wenzelm@45700
   343
            val iso = (nth recTs k, nth all_rep_names k);
haftmann@33968
   344
          in (fs', eqns', isos @ [iso]) end;
wenzelm@45700
   345
haftmann@33968
   346
        val (fs, eqns, isos) = fold process_dt ds ([], [], []);
haftmann@33968
   347
        val fTs = map fastype_of fs;
wenzelm@45700
   348
        val defs =
wenzelm@45700
   349
          map (fn (rec_name, (T, iso_name)) =>
wenzelm@46909
   350
            (Binding.name (Thm.def_name (Long_Name.base_name iso_name)),
wenzelm@45700
   351
              Logic.mk_equals (Const (iso_name, T --> Univ_elT),
wenzelm@45700
   352
                list_comb (Const (rec_name, fTs @ [T] ---> Univ_elT), fs)))) (rec_names ~~ isos);
haftmann@33968
   353
        val (def_thms, thy') =
wenzelm@52788
   354
          (Global_Theory.add_defs false o map Thm.no_attributes) defs thy;
haftmann@33968
   355
haftmann@33968
   356
        (* prove characteristic equations *)
haftmann@33968
   357
wenzelm@45878
   358
        val rewrites = def_thms @ map mk_meta_eq rec_rewrites;
wenzelm@45700
   359
        val char_thms' =
wenzelm@51551
   360
          map (fn eqn => Goal.prove_sorry_global thy' [] [] eqn
wenzelm@60752
   361
            (fn {context = ctxt, ...} =>
wenzelm@60752
   362
              EVERY [rewrite_goals_tac ctxt rewrites, resolve_tac ctxt [refl] 1])) eqns;
haftmann@33968
   363
haftmann@33968
   364
      in (thy', char_thms' @ char_thms) end;
haftmann@33968
   365
wenzelm@45700
   366
    val (thy5, iso_char_thms) =
wenzelm@52788
   367
      fold_rev make_iso_defs (tl descr) (Sign.add_path big_name thy4, []);
haftmann@33968
   368
haftmann@33968
   369
    (* prove isomorphism properties *)
haftmann@33968
   370
haftmann@33968
   371
    fun mk_funs_inv thy thm =
haftmann@33968
   372
      let
haftmann@33968
   373
        val prop = Thm.prop_of thm;
haftmann@33968
   374
        val _ $ (_ $ ((S as Const (_, Type (_, [U, _]))) $ _ )) $
haftmann@33968
   375
          (_ $ (_ $ (r $ (a $ _)) $ _)) = Type.legacy_freeze prop;
wenzelm@45738
   376
        val used = Term.add_tfree_names a [];
haftmann@33968
   377
haftmann@33968
   378
        fun mk_thm i =
haftmann@33968
   379
          let
wenzelm@56254
   380
            val Ts = map (TFree o rpair @{sort type}) (Name.variant_list used (replicate i "'t"));
wenzelm@45700
   381
            val f = Free ("f", Ts ---> U);
wenzelm@45700
   382
          in
wenzelm@51551
   383
            Goal.prove_sorry_global thy [] []
wenzelm@45700
   384
              (Logic.mk_implies
wenzelm@45700
   385
                (HOLogic.mk_Trueprop (HOLogic.list_all
blanchet@58112
   386
                   (map (pair "x") Ts, S $ Old_Datatype_Aux.app_bnds f i)),
wenzelm@46219
   387
                 HOLogic.mk_Trueprop (HOLogic.mk_eq (fold_rev (Term.abs o pair "x") Ts
blanchet@58112
   388
                   (r $ (a $ Old_Datatype_Aux.app_bnds f i)), f))))
wenzelm@60752
   389
              (fn {context = ctxt, ...} =>
wenzelm@60752
   390
                EVERY [REPEAT_DETERM_N i (resolve_tac ctxt @{thms ext} 1),
wenzelm@60752
   391
                 REPEAT (eresolve_tac ctxt [allE] 1),
wenzelm@60752
   392
                 resolve_tac ctxt [thm] 1,
wenzelm@60752
   393
                 assume_tac ctxt 1])
haftmann@33968
   394
          end
haftmann@33968
   395
      in map (fn r => r RS subst) (thm :: map mk_thm arities) end;
haftmann@33968
   396
blanchet@55417
   397
    (* prove  inj Rep_dt_i  and  Rep_dt_i x : rep_set_dt_i *)
haftmann@33968
   398
wenzelm@45700
   399
    val fun_congs =
wenzelm@59621
   400
      map (fn T => make_elim (Drule.instantiate' [SOME (Thm.global_ctyp_of thy5 T)] [] fun_cong)) branchTs;
haftmann@33968
   401
haftmann@33968
   402
    fun prove_iso_thms ds (inj_thms, elem_thms) =
haftmann@33968
   403
      let
haftmann@33968
   404
        val (_, (tname, _, _)) = hd ds;
wenzelm@45700
   405
        val induct = #induct (the (Symtab.lookup dt_info tname));
haftmann@33968
   406
haftmann@33968
   407
        fun mk_ind_concl (i, _) =
haftmann@33968
   408
          let
haftmann@33968
   409
            val T = nth recTs i;
haftmann@33968
   410
            val Rep_t = Const (nth all_rep_names i, T --> Univ_elT);
wenzelm@45700
   411
            val rep_set_name = nth rep_set_names i;
wenzelm@45879
   412
            val concl1 =
wenzelm@45879
   413
              HOLogic.all_const T $ Abs ("y", T, HOLogic.imp $
blanchet@58112
   414
                HOLogic.mk_eq (Rep_t $ Old_Datatype_Aux.mk_Free "x" T i, Rep_t $ Bound 0) $
blanchet@58112
   415
                  HOLogic.mk_eq (Old_Datatype_Aux.mk_Free "x" T i, Bound 0));
blanchet@58112
   416
            val concl2 = Const (rep_set_name, UnivT') $ (Rep_t $ Old_Datatype_Aux.mk_Free "x" T i);
wenzelm@45879
   417
          in (concl1, concl2) end;
haftmann@33968
   418
wenzelm@45879
   419
        val (ind_concl1, ind_concl2) = split_list (map mk_ind_concl ds);
haftmann@33968
   420
haftmann@33968
   421
        val rewrites = map mk_meta_eq iso_char_thms;
wenzelm@45700
   422
        val inj_thms' = map snd newT_iso_inj_thms @ map (fn r => r RS @{thm injD}) inj_thms;
haftmann@33968
   423
wenzelm@45700
   424
        val inj_thm =
wenzelm@51551
   425
          Goal.prove_sorry_global thy5 [] []
blanchet@58112
   426
            (HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj ind_concl1))
wenzelm@51798
   427
            (fn {context = ctxt, ...} => EVERY
wenzelm@60328
   428
              [(Old_Datatype_Aux.ind_tac ctxt induct [] THEN_ALL_NEW
wenzelm@60328
   429
                  Object_Logic.atomize_prems_tac ctxt) 1,
wenzelm@45700
   430
               REPEAT (EVERY
wenzelm@60752
   431
                 [resolve_tac ctxt [allI] 1, resolve_tac ctxt [impI] 1,
wenzelm@58956
   432
                  Old_Datatype_Aux.exh_tac ctxt (exh_thm_of dt_info) 1,
wenzelm@45700
   433
                  REPEAT (EVERY
wenzelm@51798
   434
                    [hyp_subst_tac ctxt 1,
wenzelm@54742
   435
                     rewrite_goals_tac ctxt rewrites,
wenzelm@59498
   436
                     REPEAT (dresolve_tac ctxt [In0_inject, In1_inject] 1),
wenzelm@59498
   437
                     (eresolve_tac ctxt [In0_not_In1 RS notE, In1_not_In0 RS notE] 1)
wenzelm@45700
   438
                     ORELSE (EVERY
wenzelm@59498
   439
                       [REPEAT (eresolve_tac ctxt (Scons_inject ::
wenzelm@45700
   440
                          map make_elim [Leaf_inject, Inl_inject, Inr_inject]) 1),
wenzelm@60752
   441
                        REPEAT (cong_tac ctxt 1), resolve_tac ctxt [refl] 1,
wenzelm@58963
   442
                        REPEAT (assume_tac ctxt 1 ORELSE (EVERY
wenzelm@60752
   443
                          [REPEAT (resolve_tac ctxt @{thms ext} 1),
wenzelm@59498
   444
                           REPEAT (eresolve_tac ctxt (mp :: allE ::
wenzelm@45700
   445
                             map make_elim (Suml_inject :: Sumr_inject ::
wenzelm@45700
   446
                               Lim_inject :: inj_thms') @ fun_congs) 1),
wenzelm@58963
   447
                           assume_tac ctxt 1]))])])])]);
haftmann@33968
   448
blanchet@58112
   449
        val inj_thms'' = map (fn r => r RS datatype_injI) (Old_Datatype_Aux.split_conj_thm inj_thm);
haftmann@33968
   450
wenzelm@45700
   451
        val elem_thm =
wenzelm@51551
   452
          Goal.prove_sorry_global thy5 [] []
blanchet@58112
   453
            (HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj ind_concl2))
wenzelm@54742
   454
            (fn {context = ctxt, ...} =>
wenzelm@54742
   455
              EVERY [
wenzelm@60328
   456
                (Old_Datatype_Aux.ind_tac ctxt induct [] THEN_ALL_NEW
wenzelm@60328
   457
                  Object_Logic.atomize_prems_tac ctxt) 1,
wenzelm@54742
   458
                rewrite_goals_tac ctxt rewrites,
wenzelm@59498
   459
                REPEAT ((resolve_tac ctxt rep_intrs THEN_ALL_NEW
wenzelm@60774
   460
                  ((REPEAT o eresolve_tac ctxt [allE]) THEN' ares_tac ctxt elem_thms)) 1)]);
haftmann@33968
   461
blanchet@58112
   462
      in (inj_thms'' @ inj_thms, elem_thms @ Old_Datatype_Aux.split_conj_thm elem_thm) end;
haftmann@33968
   463
haftmann@33968
   464
    val (iso_inj_thms_unfolded, iso_elem_thms) =
haftmann@33968
   465
      fold_rev prove_iso_thms (tl descr) ([], map #3 newT_iso_axms);
wenzelm@45700
   466
    val iso_inj_thms =
wenzelm@45700
   467
      map snd newT_iso_inj_thms @ map (fn r => r RS @{thm injD}) iso_inj_thms_unfolded;
haftmann@33968
   468
blanchet@55417
   469
    (* prove  rep_set_dt_i x --> x : range Rep_dt_i *)
haftmann@33968
   470
haftmann@33968
   471
    fun mk_iso_t (((set_name, iso_name), i), T) =
wenzelm@45700
   472
      let val isoT = T --> Univ_elT in
wenzelm@45700
   473
        HOLogic.imp $
blanchet@58112
   474
          (Const (set_name, UnivT') $ Old_Datatype_Aux.mk_Free "x" Univ_elT i) $
wenzelm@45740
   475
            (if i < length newTs then @{term True}
blanchet@58112
   476
             else HOLogic.mk_mem (Old_Datatype_Aux.mk_Free "x" Univ_elT i,
wenzelm@45700
   477
               Const (@{const_name image}, isoT --> HOLogic.mk_setT T --> UnivT) $
wenzelm@45700
   478
                 Const (iso_name, isoT) $ Const (@{const_abbrev UNIV}, HOLogic.mk_setT T)))
haftmann@33968
   479
      end;
haftmann@33968
   480
blanchet@58112
   481
    val iso_t = HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj (map mk_iso_t
haftmann@33968
   482
      (rep_set_names ~~ all_rep_names ~~ (0 upto (length descr' - 1)) ~~ recTs)));
haftmann@33968
   483
haftmann@33968
   484
    (* all the theorems are proved by one single simultaneous induction *)
haftmann@33968
   485
wenzelm@45700
   486
    val range_eqs = map (fn r => mk_meta_eq (r RS @{thm range_ex1_eq})) iso_inj_thms_unfolded;
haftmann@33968
   487
wenzelm@45700
   488
    val iso_thms =
wenzelm@45700
   489
      if length descr = 1 then []
wenzelm@45700
   490
      else
blanchet@58112
   491
        drop (length newTs) (Old_Datatype_Aux.split_conj_thm
wenzelm@51798
   492
          (Goal.prove_sorry_global thy5 [] [] iso_t (fn {context = ctxt, ...} => EVERY
wenzelm@60328
   493
             [(Old_Datatype_Aux.ind_tac ctxt rep_induct [] THEN_ALL_NEW
blanchet@58112
   494
                 Object_Logic.atomize_prems_tac ctxt) 1,
wenzelm@60752
   495
              REPEAT (resolve_tac ctxt [TrueI] 1),
wenzelm@54742
   496
              rewrite_goals_tac ctxt (mk_meta_eq @{thm choice_eq} ::
wenzelm@45700
   497
                Thm.symmetric (mk_meta_eq @{thm fun_eq_iff}) :: range_eqs),
wenzelm@54742
   498
              rewrite_goals_tac ctxt (map Thm.symmetric range_eqs),
wenzelm@45700
   499
              REPEAT (EVERY
wenzelm@59498
   500
                [REPEAT (eresolve_tac ctxt ([rangeE, @{thm ex1_implies_ex} RS exE] @
wenzelm@45700
   501
                   maps (mk_funs_inv thy5 o #1) newT_iso_axms) 1),
wenzelm@51798
   502
                 TRY (hyp_subst_tac ctxt 1),
wenzelm@60752
   503
                 resolve_tac ctxt [sym RS range_eqI] 1,
wenzelm@59498
   504
                 resolve_tac ctxt iso_char_thms 1])])));
haftmann@33968
   505
haftmann@33968
   506
    val Abs_inverse_thms' =
haftmann@33968
   507
      map #1 newT_iso_axms @
haftmann@33968
   508
      map2 (fn r_inj => fn r => @{thm f_the_inv_into_f} OF [r_inj, r RS mp])
haftmann@33968
   509
        iso_inj_thms_unfolded iso_thms;
haftmann@33968
   510
haftmann@33968
   511
    val Abs_inverse_thms = maps (mk_funs_inv thy5) Abs_inverse_thms';
haftmann@33968
   512
haftmann@33968
   513
    (******************* freeness theorems for constructors *******************)
haftmann@33968
   514
blanchet@58112
   515
    val _ = Old_Datatype_Aux.message config "Proving freeness of constructors ...";
haftmann@33968
   516
haftmann@33968
   517
    (* prove theorem  Rep_i (Constr_j ...) = Inj_j ...  *)
wenzelm@45700
   518
haftmann@33968
   519
    fun prove_constr_rep_thm eqn =
haftmann@33968
   520
      let
haftmann@33968
   521
        val inj_thms = map fst newT_iso_inj_thms;
wenzelm@45878
   522
        val rewrites = @{thm o_def} :: constr_defs @ map (mk_meta_eq o #2) newT_iso_axms;
wenzelm@45700
   523
      in
wenzelm@51551
   524
        Goal.prove_sorry_global thy5 [] [] eqn
wenzelm@54742
   525
        (fn {context = ctxt, ...} => EVERY
wenzelm@59498
   526
          [resolve_tac ctxt inj_thms 1,
wenzelm@54742
   527
           rewrite_goals_tac ctxt rewrites,
wenzelm@60752
   528
           resolve_tac ctxt [refl] 3,
wenzelm@59498
   529
           resolve_tac ctxt rep_intrs 2,
wenzelm@59498
   530
           REPEAT (resolve_tac ctxt iso_elem_thms 1)])
haftmann@33968
   531
      end;
haftmann@33968
   532
haftmann@33968
   533
    (*--------------------------------------------------------------*)
haftmann@33968
   534
    (* constr_rep_thms and rep_congs are used to prove distinctness *)
haftmann@33968
   535
    (* of constructors.                                             *)
haftmann@33968
   536
    (*--------------------------------------------------------------*)
haftmann@33968
   537
haftmann@33968
   538
    val constr_rep_thms = map (map prove_constr_rep_thm) constr_rep_eqns;
haftmann@33968
   539
wenzelm@45700
   540
    val dist_rewrites =
wenzelm@45700
   541
      map (fn (rep_thms, dist_lemma) =>
wenzelm@45878
   542
        dist_lemma :: (rep_thms @ [In0_eq, In1_eq, In0_not_In1, In1_not_In0]))
wenzelm@45700
   543
          (constr_rep_thms ~~ dist_lemmas);
haftmann@33968
   544
wenzelm@45889
   545
    fun prove_distinct_thms dist_rewrites' =
haftmann@33968
   546
      let
haftmann@33968
   547
        fun prove [] = []
haftmann@33968
   548
          | prove (t :: ts) =
haftmann@33968
   549
              let
wenzelm@51717
   550
                val dist_thm = Goal.prove_sorry_global thy5 [] [] t (fn {context = ctxt, ...} =>
wenzelm@51717
   551
                  EVERY [simp_tac (put_simpset HOL_ss ctxt addsimps dist_rewrites') 1])
wenzelm@45910
   552
              in dist_thm :: Drule.zero_var_indexes (dist_thm RS not_sym) :: prove ts end;
wenzelm@45889
   553
      in prove end;
haftmann@33968
   554
wenzelm@45700
   555
    val distinct_thms =
blanchet@58112
   556
      map2 (prove_distinct_thms) dist_rewrites (Old_Datatype_Prop.make_distincts descr);
haftmann@33968
   557
haftmann@33968
   558
    (* prove injectivity of constructors *)
haftmann@33968
   559
haftmann@33968
   560
    fun prove_constr_inj_thm rep_thms t =
wenzelm@45700
   561
      let
wenzelm@45700
   562
        val inj_thms = Scons_inject ::
wenzelm@45700
   563
          map make_elim
wenzelm@45700
   564
            (iso_inj_thms @
wenzelm@45700
   565
              [In0_inject, In1_inject, Leaf_inject, Inl_inject, Inr_inject,
wenzelm@45700
   566
               Lim_inject, Suml_inject, Sumr_inject])
wenzelm@45700
   567
      in
wenzelm@51551
   568
        Goal.prove_sorry_global thy5 [] [] t
wenzelm@51798
   569
          (fn {context = ctxt, ...} => EVERY
wenzelm@60752
   570
            [resolve_tac ctxt [iffI] 1,
wenzelm@60752
   571
             REPEAT (eresolve_tac ctxt [conjE] 2), hyp_subst_tac ctxt 2,
wenzelm@60752
   572
             resolve_tac ctxt [refl] 2,
wenzelm@60752
   573
             dresolve_tac ctxt rep_congs 1,
wenzelm@60752
   574
             dresolve_tac ctxt @{thms box_equals} 1,
wenzelm@59498
   575
             REPEAT (resolve_tac ctxt rep_thms 1),
wenzelm@59498
   576
             REPEAT (eresolve_tac ctxt inj_thms 1),
wenzelm@60774
   577
             REPEAT (ares_tac ctxt [conjI] 1 ORELSE (EVERY [REPEAT (resolve_tac ctxt @{thms ext} 1),
wenzelm@59498
   578
               REPEAT (eresolve_tac ctxt (make_elim fun_cong :: inj_thms) 1),
wenzelm@58963
   579
               assume_tac ctxt 1]))])
haftmann@33968
   580
      end;
haftmann@33968
   581
wenzelm@45700
   582
    val constr_inject =
wenzelm@45700
   583
      map (fn (ts, thms) => map (prove_constr_inj_thm thms) ts)
blanchet@58112
   584
        (Old_Datatype_Prop.make_injs descr ~~ constr_rep_thms);
haftmann@33968
   585
haftmann@33968
   586
    val ((constr_inject', distinct_thms'), thy6) =
haftmann@33968
   587
      thy5
haftmann@33968
   588
      |> Sign.parent_path
blanchet@58112
   589
      |> Old_Datatype_Aux.store_thmss "inject" new_type_names constr_inject
blanchet@58112
   590
      ||>> Old_Datatype_Aux.store_thmss "distinct" new_type_names distinct_thms;
haftmann@33968
   591
haftmann@33968
   592
    (*************************** induction theorem ****************************)
haftmann@33968
   593
blanchet@58112
   594
    val _ = Old_Datatype_Aux.message config "Proving induction rule for datatypes ...";
haftmann@33968
   595
wenzelm@45700
   596
    val Rep_inverse_thms =
wenzelm@45700
   597
      map (fn (_, iso, _) => iso RS subst) newT_iso_axms @
wenzelm@45700
   598
      map (fn r => r RS @{thm the_inv_f_f} RS subst) iso_inj_thms_unfolded;
haftmann@33968
   599
    val Rep_inverse_thms' = map (fn r => r RS @{thm the_inv_f_f}) iso_inj_thms_unfolded;
haftmann@33968
   600
wenzelm@45879
   601
    fun mk_indrule_lemma (i, _) T =
haftmann@33968
   602
      let
blanchet@58112
   603
        val Rep_t = Const (nth all_rep_names i, T --> Univ_elT) $ Old_Datatype_Aux.mk_Free "x" T i;
wenzelm@45700
   604
        val Abs_t =
wenzelm@45700
   605
          if i < length newTs then
wenzelm@45879
   606
            Const (#Abs_name (#1 (#2 (nth typedefs i))), Univ_elT --> T)
wenzelm@45879
   607
          else
wenzelm@45879
   608
            Const (@{const_name the_inv_into},
haftmann@33968
   609
              [HOLogic.mk_setT T, T --> Univ_elT, Univ_elT] ---> T) $
wenzelm@45700
   610
            HOLogic.mk_UNIV T $ Const (nth all_rep_names i, T --> Univ_elT);
wenzelm@45879
   611
        val prem =
wenzelm@45879
   612
          HOLogic.imp $
haftmann@33968
   613
            (Const (nth rep_set_names i, UnivT') $ Rep_t) $
blanchet@58112
   614
              (Old_Datatype_Aux.mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ (Abs_t $ Rep_t));
wenzelm@45879
   615
        val concl =
blanchet@58112
   616
          Old_Datatype_Aux.mk_Free "P" (T --> HOLogic.boolT) (i + 1) $
blanchet@58112
   617
            Old_Datatype_Aux.mk_Free "x" T i;
wenzelm@45879
   618
      in (prem, concl) end;
haftmann@33968
   619
haftmann@33968
   620
    val (indrule_lemma_prems, indrule_lemma_concls) =
wenzelm@45879
   621
      split_list (map2 mk_indrule_lemma descr' recTs);
haftmann@33968
   622
wenzelm@45700
   623
    val indrule_lemma =
wenzelm@51551
   624
      Goal.prove_sorry_global thy6 [] []
wenzelm@45700
   625
        (Logic.mk_implies
blanchet@58112
   626
          (HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj indrule_lemma_prems),
blanchet@58112
   627
           HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj indrule_lemma_concls)))
wenzelm@59498
   628
        (fn {context = ctxt, ...} =>
wenzelm@45700
   629
          EVERY
wenzelm@60752
   630
           [REPEAT (eresolve_tac ctxt [conjE] 1),
haftmann@33968
   631
            REPEAT (EVERY
wenzelm@60752
   632
              [TRY (resolve_tac ctxt [conjI] 1), resolve_tac ctxt Rep_inverse_thms 1,
wenzelm@60752
   633
               eresolve_tac ctxt [mp] 1, resolve_tac ctxt iso_elem_thms 1])]);
haftmann@33968
   634
wenzelm@59582
   635
    val Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of indrule_lemma)));
wenzelm@45700
   636
    val frees =
wenzelm@45700
   637
      if length Ps = 1 then [Free ("P", snd (dest_Var (hd Ps)))]
wenzelm@45700
   638
      else map (Free o apfst fst o dest_Var) Ps;
haftmann@33968
   639
blanchet@58112
   640
    val dt_induct_prop = Old_Datatype_Prop.make_ind descr;
wenzelm@45700
   641
    val dt_induct =
wenzelm@51551
   642
      Goal.prove_sorry_global thy6 []
wenzelm@45700
   643
      (Logic.strip_imp_prems dt_induct_prop)
wenzelm@45700
   644
      (Logic.strip_imp_concl dt_induct_prop)
wenzelm@51717
   645
      (fn {context = ctxt, prems, ...} =>
wenzelm@60781
   646
        let
wenzelm@60781
   647
          val indrule_lemma' =
wenzelm@60781
   648
            infer_instantiate ctxt
wenzelm@60781
   649
              (map (#1 o dest_Var) Ps ~~ map (Thm.cterm_of ctxt) frees) indrule_lemma;
wenzelm@60781
   650
        in
wenzelm@60781
   651
          EVERY
wenzelm@60781
   652
            [resolve_tac ctxt [indrule_lemma'] 1,
wenzelm@60781
   653
             (Old_Datatype_Aux.ind_tac ctxt rep_induct [] THEN_ALL_NEW
wenzelm@60781
   654
                Object_Logic.atomize_prems_tac ctxt) 1,
wenzelm@60781
   655
             EVERY (map (fn (prem, r) => (EVERY
wenzelm@60781
   656
               [REPEAT (eresolve_tac ctxt Abs_inverse_thms 1),
wenzelm@60781
   657
                simp_tac (put_simpset HOL_basic_ss ctxt
wenzelm@60781
   658
                  addsimps (Thm.symmetric r :: Rep_inverse_thms')) 1,
wenzelm@60781
   659
                DEPTH_SOLVE_1 (ares_tac ctxt [prem] 1 ORELSE eresolve_tac ctxt [allE] 1)]))
wenzelm@60781
   660
                    (prems ~~ (constr_defs @ map mk_meta_eq iso_char_thms)))]
wenzelm@60781
   661
        end);
haftmann@33968
   662
wenzelm@45901
   663
    val ([(_, [dt_induct'])], thy7) =
haftmann@33968
   664
      thy6
wenzelm@45901
   665
      |> Global_Theory.note_thmss ""
wenzelm@45901
   666
        [((Binding.qualify true big_name (Binding.name "induct"), [case_names_induct]),
wenzelm@52788
   667
          [([dt_induct], [])])];
haftmann@33968
   668
  in
haftmann@33968
   669
    ((constr_inject', distinct_thms', dt_induct'), thy7)
haftmann@33968
   670
  end;
haftmann@33968
   671
haftmann@33968
   672
haftmann@33968
   673
wenzelm@45701
   674
(** datatype definition **)
haftmann@33968
   675
wenzelm@45839
   676
(* specifications *)
wenzelm@45839
   677
wenzelm@45839
   678
type spec_cmd =
wenzelm@45839
   679
  (binding * (string * string option) list * mixfix) * (binding * string list * mixfix) list;
wenzelm@45839
   680
wenzelm@45839
   681
local
wenzelm@45839
   682
wenzelm@45839
   683
fun parse_spec ctxt ((b, args, mx), constrs) =
wenzelm@45839
   684
  ((b, map (apsnd (Typedecl.read_constraint ctxt)) args, mx),
wenzelm@45839
   685
    constrs |> map (fn (c, Ts, mx') => (c, map (Syntax.parse_typ ctxt) Ts, mx')));
wenzelm@45839
   686
blanchet@58114
   687
fun check_specs ctxt (specs: Old_Datatype_Aux.spec list) =
wenzelm@45839
   688
  let
wenzelm@45839
   689
    fun prep_spec ((tname, args, mx), constrs) tys =
wenzelm@45839
   690
      let
wenzelm@45839
   691
        val (args', tys1) = chop (length args) tys;
wenzelm@45839
   692
        val (constrs', tys3) = (constrs, tys1) |-> fold_map (fn (cname, cargs, mx') => fn tys2 =>
wenzelm@45839
   693
          let val (cargs', tys3) = chop (length cargs) tys2;
wenzelm@45839
   694
          in ((cname, cargs', mx'), tys3) end);
wenzelm@45839
   695
      in (((tname, map dest_TFree args', mx), constrs'), tys3) end;
wenzelm@45839
   696
wenzelm@45839
   697
    val all_tys =
wenzelm@45839
   698
      specs |> maps (fn ((_, args, _), cs) => map TFree args @ maps #2 cs)
wenzelm@45839
   699
      |> Syntax.check_typs ctxt;
wenzelm@45839
   700
wenzelm@45839
   701
  in #1 (fold_map prep_spec specs all_tys) end;
wenzelm@45839
   702
wenzelm@45839
   703
fun prep_specs parse raw_specs thy =
wenzelm@45839
   704
  let
wenzelm@45839
   705
    val ctxt = thy
wenzelm@45839
   706
      |> Sign.add_types_global (map (fn ((b, args, mx), _) => (b, length args, mx)) raw_specs)
wenzelm@45839
   707
      |> Proof_Context.init_global
wenzelm@45839
   708
      |> fold (fn ((_, args, _), _) => fold (fn (a, _) =>
wenzelm@45839
   709
          Variable.declare_typ (TFree (a, dummyS))) args) raw_specs;
wenzelm@45839
   710
    val specs = check_specs ctxt (map (parse ctxt) raw_specs);
wenzelm@45839
   711
  in (specs, ctxt) end;
wenzelm@45839
   712
wenzelm@45839
   713
in
wenzelm@45839
   714
wenzelm@45839
   715
val read_specs = prep_specs parse_spec;
wenzelm@45839
   716
val check_specs = prep_specs (K I);
wenzelm@45839
   717
wenzelm@45839
   718
end;
wenzelm@45839
   719
wenzelm@45839
   720
wenzelm@45839
   721
(* main commands *)
wenzelm@45839
   722
wenzelm@45839
   723
fun gen_add_datatype prep_specs config raw_specs thy =
haftmann@33968
   724
  let
wenzelm@45839
   725
    val (dts, spec_ctxt) = prep_specs raw_specs thy;
wenzelm@45839
   726
    val ((_, tyvars, _), _) :: _ = dts;
wenzelm@45839
   727
    val string_of_tyvar = Syntax.string_of_typ spec_ctxt o TFree;
haftmann@33968
   728
wenzelm@45839
   729
    val (new_dts, types_syntax) = dts |> map (fn ((tname, tvs, mx), _) =>
wenzelm@45839
   730
      let val full_tname = Sign.full_name thy tname in
haftmann@33968
   731
        (case duplicates (op =) tvs of
haftmann@33968
   732
          [] =>
haftmann@33968
   733
            if eq_set (op =) (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
wenzelm@45839
   734
            else error "Mutually recursive datatypes must have same type parameters"
wenzelm@45700
   735
        | dups =>
wenzelm@45700
   736
            error ("Duplicate parameter(s) for datatype " ^ Binding.print tname ^
wenzelm@45839
   737
              " : " ^ commas (map string_of_tyvar dups)))
wenzelm@45839
   738
      end) |> split_list;
haftmann@33968
   739
    val dt_names = map fst new_dts;
haftmann@33968
   740
haftmann@33968
   741
    val _ =
wenzelm@45701
   742
      (case duplicates (op =) (map fst new_dts) of
haftmann@33968
   743
        [] => ()
wenzelm@45822
   744
      | dups => error ("Duplicate datatypes: " ^ commas_quote dups));
haftmann@33968
   745
wenzelm@45889
   746
    fun prep_dt_spec ((tname, tvs, _), constrs) (dts', constr_syntax, i) =
haftmann@33968
   747
      let
wenzelm@45889
   748
        fun prep_constr (cname, cargs, mx) (constrs, constr_syntax') =
haftmann@33968
   749
          let
haftmann@33968
   750
            val _ =
wenzelm@45839
   751
              (case subtract (op =) tvs (fold Term.add_tfreesT cargs []) of
haftmann@33968
   752
                [] => ()
wenzelm@45839
   753
              | vs => error ("Extra type variables on rhs: " ^ commas (map string_of_tyvar vs)));
wenzelm@45839
   754
            val c = Sign.full_name_path thy (Binding.name_of tname) cname;
wenzelm@35129
   755
          in
blanchet@58112
   756
            (constrs @ [(c, map (Old_Datatype_Aux.dtyp_of_typ new_dts) cargs)],
wenzelm@45889
   757
              constr_syntax' @ [(cname, mx)])
wenzelm@45700
   758
          end handle ERROR msg =>
wenzelm@45700
   759
            cat_error msg ("The error above occurred in constructor " ^ Binding.print cname ^
wenzelm@45700
   760
              " of datatype " ^ Binding.print tname);
haftmann@33968
   761
wenzelm@45839
   762
        val (constrs', constr_syntax') = fold prep_constr constrs ([], []);
haftmann@33968
   763
      in
wenzelm@45700
   764
        (case duplicates (op =) (map fst constrs') of
wenzelm@35129
   765
          [] =>
blanchet@58112
   766
            (dts' @ [(i, (Sign.full_name thy tname, map Old_Datatype_Aux.DtTFree tvs, constrs'))],
wenzelm@45839
   767
              constr_syntax @ [constr_syntax'], i + 1)
wenzelm@42381
   768
        | dups =>
wenzelm@45822
   769
            error ("Duplicate constructors " ^ commas_quote dups ^
wenzelm@45822
   770
              " in datatype " ^ Binding.print tname))
haftmann@33968
   771
      end;
haftmann@33968
   772
wenzelm@45839
   773
    val (dts', constr_syntax, i) = fold prep_dt_spec dts ([], [], 0);
wenzelm@45822
   774
blanchet@58112
   775
    val dt_info = Old_Datatype_Data.get_all thy;
blanchet@58112
   776
    val (descr, _) = Old_Datatype_Aux.unfold_datatypes spec_ctxt dts' dt_info dts' i;
wenzelm@41423
   777
    val _ =
blanchet@58112
   778
      Old_Datatype_Aux.check_nonempty descr
blanchet@58112
   779
        handle (exn as Old_Datatype_Aux.Datatype_Empty s) =>
wenzelm@45822
   780
          if #strict config then error ("Nonemptiness check failed for datatype " ^ quote s)
wenzelm@41423
   781
          else reraise exn;
haftmann@33968
   782
wenzelm@45701
   783
    val _ =
blanchet@58112
   784
      Old_Datatype_Aux.message config
wenzelm@45839
   785
        ("Constructing datatype(s) " ^ commas_quote (map (Binding.name_of o #1 o #1) dts));
haftmann@33968
   786
  in
haftmann@33968
   787
    thy
wenzelm@45822
   788
    |> representation_proofs config dt_info descr types_syntax constr_syntax
blanchet@58112
   789
      (Old_Datatype_Data.mk_case_names_induct (flat descr))
wenzelm@45700
   790
    |-> (fn (inject, distinct, induct) =>
blanchet@58112
   791
      Old_Rep_Datatype.derive_datatype_props config dt_names descr induct inject distinct)
haftmann@33968
   792
  end;
haftmann@33968
   793
wenzelm@45839
   794
val add_datatype = gen_add_datatype check_specs;
wenzelm@45863
   795
val add_datatype_cmd = gen_add_datatype read_specs;
haftmann@33968
   796
wenzelm@45701
   797
wenzelm@45839
   798
(* outer syntax *)
haftmann@33968
   799
wenzelm@45839
   800
val spec_cmd =
wenzelm@45839
   801
  Parse.type_args_constrained -- Parse.binding -- Parse.opt_mixfix --
wenzelm@46949
   802
  (@{keyword "="} |-- Parse.enum1 "|" (Parse.binding -- Scan.repeat Parse.typ -- Parse.opt_mixfix))
wenzelm@45839
   803
  >> (fn (((vs, t), mx), cons) => ((t, vs, mx), map Parse.triple1 cons));
haftmann@33968
   804
haftmann@33968
   805
val _ =
wenzelm@59936
   806
  Outer_Syntax.command @{command_keyword old_datatype} "define old-style inductive datatypes"
wenzelm@45863
   807
    (Parse.and_list1 spec_cmd
blanchet@58112
   808
      >> (Toplevel.theory o (snd oo add_datatype_cmd Old_Datatype_Aux.default_config)));
wenzelm@41423
   809
blanchet@58114
   810
open Old_Datatype_Aux;
blanchet@58114
   811
haftmann@33968
   812
end;