src/HOL/Tools/Datatype/datatype.ML
changeset 33968 f94fb13ecbb3
parent 33963 977b94b64905
child 33969 1e7ca47c6c3d
     1.1 --- a/src/HOL/Tools/Datatype/datatype.ML	Mon Nov 30 11:42:48 2009 +0100
     1.2 +++ b/src/HOL/Tools/Datatype/datatype.ML	Mon Nov 30 11:42:49 2009 +0100
     1.3 @@ -1,19 +1,748 @@
     1.4 -(*  Title:      HOL/Tools/datatype.ML
     1.5 +(*  Title:      HOL/Tools/Datatype/datatype.ML
     1.6      Author:     Stefan Berghofer, TU Muenchen
     1.7  
     1.8 -Datatype package interface for Isabelle/HOL.
     1.9 +Datatype package: definitional introduction of datatypes
    1.10 +with proof of characteristic theorems: injectivity / distinctness
    1.11 +of constructors and induction.  Main interface to datatypes
    1.12 +after full bootstrap of datatype package.
    1.13  *)
    1.14  
    1.15  signature DATATYPE =
    1.16  sig
    1.17    include DATATYPE_DATA
    1.18 -  include DATATYPE_REP_PROOFS
    1.19 +  val add_datatype : config -> string list -> (string list * binding * mixfix *
    1.20 +    (binding * typ list * mixfix) list) list -> theory -> string list * theory
    1.21 +  val datatype_cmd : string list -> (string list * binding * mixfix *
    1.22 +    (binding * string list * mixfix) list) list -> theory -> theory
    1.23  end;
    1.24  
    1.25 -structure Datatype =
    1.26 +structure Datatype : DATATYPE =
    1.27  struct
    1.28  
    1.29 +(** auxiliary **)
    1.30 +
    1.31 +open Datatype_Aux;
    1.32  open Datatype_Data;
    1.33 -open DatatypeRepProofs;
    1.34 +
    1.35 +val (_ $ (_ $ (_ $ (distinct_f $ _) $ _))) = hd (prems_of distinct_lemma);
    1.36 +
    1.37 +val collect_simp = rewrite_rule [mk_meta_eq mem_Collect_eq];
    1.38 +
    1.39 +fun exh_thm_of (dt_info : info Symtab.table) tname =
    1.40 +  #exhaust (the (Symtab.lookup dt_info tname));
    1.41 +
    1.42 +val node_name = @{type_name "Datatype.node"};
    1.43 +val In0_name = @{const_name "Datatype.In0"};
    1.44 +val In1_name = @{const_name "Datatype.In1"};
    1.45 +val Scons_name = @{const_name "Datatype.Scons"};
    1.46 +val Leaf_name = @{const_name "Datatype.Leaf"};
    1.47 +val Numb_name = @{const_name "Datatype.Numb"};
    1.48 +val Lim_name = @{const_name "Datatype.Lim"};
    1.49 +val Suml_name = @{const_name "Sum_Type.Suml"};
    1.50 +val Sumr_name = @{const_name "Sum_Type.Sumr"};
    1.51 +
    1.52 +val In0_inject = @{thm In0_inject};
    1.53 +val In1_inject = @{thm In1_inject};
    1.54 +val Scons_inject = @{thm Scons_inject};
    1.55 +val Leaf_inject = @{thm Leaf_inject};
    1.56 +val In0_eq = @{thm In0_eq};
    1.57 +val In1_eq = @{thm In1_eq};
    1.58 +val In0_not_In1 = @{thm In0_not_In1};
    1.59 +val In1_not_In0 = @{thm In1_not_In0};
    1.60 +val Lim_inject = @{thm Lim_inject};
    1.61 +val Inl_inject = @{thm Inl_inject};
    1.62 +val Inr_inject = @{thm Inr_inject};
    1.63 +val Suml_inject = @{thm Suml_inject};
    1.64 +val Sumr_inject = @{thm Sumr_inject};
    1.65 +
    1.66 +
    1.67 +
    1.68 +(** proof of characteristic theorems **)
    1.69 +
    1.70 +fun representation_proofs (config : config) (dt_info : info Symtab.table)
    1.71 +      new_type_names descr sorts types_syntax constr_syntax case_names_induct thy =
    1.72 +  let
    1.73 +    val descr' = flat descr;
    1.74 +    val big_name = space_implode "_" new_type_names;
    1.75 +    val thy1 = Sign.add_path big_name thy;
    1.76 +    val big_rec_name = big_name ^ "_rep_set";
    1.77 +    val rep_set_names' =
    1.78 +      (if length descr' = 1 then [big_rec_name] else
    1.79 +        (map ((curry (op ^) (big_rec_name ^ "_")) o string_of_int)
    1.80 +          (1 upto (length descr'))));
    1.81 +    val rep_set_names = map (Sign.full_bname thy1) rep_set_names';
    1.82 +
    1.83 +    val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
    1.84 +    val leafTs' = get_nonrec_types descr' sorts;
    1.85 +    val branchTs = get_branching_types descr' sorts;
    1.86 +    val branchT = if null branchTs then HOLogic.unitT
    1.87 +      else Balanced_Tree.make (fn (T, U) => Type ("+", [T, U])) branchTs;
    1.88 +    val arities = remove (op =) 0 (get_arities descr');
    1.89 +    val unneeded_vars =
    1.90 +      subtract (op =) (List.foldr OldTerm.add_typ_tfree_names [] (leafTs' @ branchTs)) (hd tyvars);
    1.91 +    val leafTs = leafTs' @ map (fn n => TFree (n, (the o AList.lookup (op =) sorts) n)) unneeded_vars;
    1.92 +    val recTs = get_rec_types descr' sorts;
    1.93 +    val (newTs, oldTs) = chop (length (hd descr)) recTs;
    1.94 +    val sumT = if null leafTs then HOLogic.unitT
    1.95 +      else Balanced_Tree.make (fn (T, U) => Type ("+", [T, U])) leafTs;
    1.96 +    val Univ_elT = HOLogic.mk_setT (Type (node_name, [sumT, branchT]));
    1.97 +    val UnivT = HOLogic.mk_setT Univ_elT;
    1.98 +    val UnivT' = Univ_elT --> HOLogic.boolT;
    1.99 +    val Collect = Const (@{const_name Collect}, UnivT' --> UnivT);
   1.100 +
   1.101 +    val In0 = Const (In0_name, Univ_elT --> Univ_elT);
   1.102 +    val In1 = Const (In1_name, Univ_elT --> Univ_elT);
   1.103 +    val Leaf = Const (Leaf_name, sumT --> Univ_elT);
   1.104 +    val Lim = Const (Lim_name, (branchT --> Univ_elT) --> Univ_elT);
   1.105 +
   1.106 +    (* make injections needed for embedding types in leaves *)
   1.107 +
   1.108 +    fun mk_inj T' x =
   1.109 +      let
   1.110 +        fun mk_inj' T n i =
   1.111 +          if n = 1 then x else
   1.112 +          let val n2 = n div 2;
   1.113 +              val Type (_, [T1, T2]) = T
   1.114 +          in
   1.115 +            if i <= n2 then
   1.116 +              Const (@{const_name "Sum_Type.Inl"}, T1 --> T) $ (mk_inj' T1 n2 i)
   1.117 +            else
   1.118 +              Const (@{const_name "Sum_Type.Inr"}, T2 --> T) $ (mk_inj' T2 (n - n2) (i - n2))
   1.119 +          end
   1.120 +      in mk_inj' sumT (length leafTs) (1 + find_index (fn T'' => T'' = T') leafTs)
   1.121 +      end;
   1.122 +
   1.123 +    (* make injections for constructors *)
   1.124 +
   1.125 +    fun mk_univ_inj ts = Balanced_Tree.access
   1.126 +      {left = fn t => In0 $ t,
   1.127 +        right = fn t => In1 $ t,
   1.128 +        init =
   1.129 +          if ts = [] then Const (@{const_name undefined}, Univ_elT)
   1.130 +          else foldr1 (HOLogic.mk_binop Scons_name) ts};
   1.131 +
   1.132 +    (* function spaces *)
   1.133 +
   1.134 +    fun mk_fun_inj T' x =
   1.135 +      let
   1.136 +        fun mk_inj T n i =
   1.137 +          if n = 1 then x else
   1.138 +          let
   1.139 +            val n2 = n div 2;
   1.140 +            val Type (_, [T1, T2]) = T;
   1.141 +            fun mkT U = (U --> Univ_elT) --> T --> Univ_elT
   1.142 +          in
   1.143 +            if i <= n2 then Const (Suml_name, mkT T1) $ mk_inj T1 n2 i
   1.144 +            else Const (Sumr_name, mkT T2) $ mk_inj T2 (n - n2) (i - n2)
   1.145 +          end
   1.146 +      in mk_inj branchT (length branchTs) (1 + find_index (fn T'' => T'' = T') branchTs)
   1.147 +      end;
   1.148 +
   1.149 +    fun mk_lim t Ts = fold_rev (fn T => fn t => Lim $ mk_fun_inj T (Abs ("x", T, t))) Ts t;
   1.150 +
   1.151 +    (************** generate introduction rules for representing set **********)
   1.152 +
   1.153 +    val _ = message config "Constructing representing sets ...";
   1.154 +
   1.155 +    (* make introduction rule for a single constructor *)
   1.156 +
   1.157 +    fun make_intr s n (i, (_, cargs)) =
   1.158 +      let
   1.159 +        fun mk_prem dt (j, prems, ts) =
   1.160 +          (case strip_dtyp dt of
   1.161 +            (dts, DtRec k) =>
   1.162 +              let
   1.163 +                val Ts = map (typ_of_dtyp descr' sorts) dts;
   1.164 +                val free_t =
   1.165 +                  app_bnds (mk_Free "x" (Ts ---> Univ_elT) j) (length Ts)
   1.166 +              in (j + 1, list_all (map (pair "x") Ts,
   1.167 +                  HOLogic.mk_Trueprop
   1.168 +                    (Free (nth rep_set_names' k, UnivT') $ free_t)) :: prems,
   1.169 +                mk_lim free_t Ts :: ts)
   1.170 +              end
   1.171 +          | _ =>
   1.172 +              let val T = typ_of_dtyp descr' sorts dt
   1.173 +              in (j + 1, prems, (Leaf $ mk_inj T (mk_Free "x" T j))::ts)
   1.174 +              end);
   1.175 +
   1.176 +        val (_, prems, ts) = fold_rev mk_prem cargs (1, [], []);
   1.177 +        val concl = HOLogic.mk_Trueprop
   1.178 +          (Free (s, UnivT') $ mk_univ_inj ts n i)
   1.179 +      in Logic.list_implies (prems, concl)
   1.180 +      end;
   1.181 +
   1.182 +    val intr_ts = maps (fn ((_, (_, _, constrs)), rep_set_name) =>
   1.183 +      map (make_intr rep_set_name (length constrs))
   1.184 +        ((1 upto (length constrs)) ~~ constrs)) (descr' ~~ rep_set_names');
   1.185 +
   1.186 +    val ({raw_induct = rep_induct, intrs = rep_intrs, ...}, thy2) =
   1.187 +      thy1
   1.188 +      |> Sign.map_naming Name_Space.conceal
   1.189 +      |> Inductive.add_inductive_global
   1.190 +          {quiet_mode = #quiet config, verbose = false, alt_name = Binding.name big_rec_name,
   1.191 +           coind = false, no_elim = true, no_ind = false, skip_mono = true, fork_mono = false}
   1.192 +          (map (fn s => ((Binding.name s, UnivT'), NoSyn)) rep_set_names') []
   1.193 +          (map (fn x => (Attrib.empty_binding, x)) intr_ts) []
   1.194 +      ||> Sign.restore_naming thy1
   1.195 +      ||> Theory.checkpoint;
   1.196 +
   1.197 +    (********************************* typedef ********************************)
   1.198 +
   1.199 +    val (typedefs, thy3) = thy2 |>
   1.200 +      Sign.parent_path |>
   1.201 +      fold_map (fn ((((name, mx), tvs), c), name') =>
   1.202 +          Typedef.add_typedef false (SOME (Binding.name name')) (name, tvs, mx)
   1.203 +            (Collect $ Const (c, UnivT')) NONE
   1.204 +            (rtac exI 1 THEN rtac CollectI 1 THEN
   1.205 +              QUIET_BREADTH_FIRST (has_fewer_prems 1)
   1.206 +              (resolve_tac rep_intrs 1)))
   1.207 +                (types_syntax ~~ tyvars ~~
   1.208 +                  (take (length newTs) rep_set_names) ~~ new_type_names) ||>
   1.209 +      Sign.add_path big_name;
   1.210 +
   1.211 +    (*********************** definition of constructors ***********************)
   1.212 +
   1.213 +    val big_rep_name = (space_implode "_" new_type_names) ^ "_Rep_";
   1.214 +    val rep_names = map (curry op ^ "Rep_") new_type_names;
   1.215 +    val rep_names' = map (fn i => big_rep_name ^ (string_of_int i))
   1.216 +      (1 upto (length (flat (tl descr))));
   1.217 +    val all_rep_names = map (Sign.intern_const thy3) rep_names @
   1.218 +      map (Sign.full_bname thy3) rep_names';
   1.219 +
   1.220 +    (* isomorphism declarations *)
   1.221 +
   1.222 +    val iso_decls = map (fn (T, s) => (Binding.name s, T --> Univ_elT, NoSyn))
   1.223 +      (oldTs ~~ rep_names');
   1.224 +
   1.225 +    (* constructor definitions *)
   1.226 +
   1.227 +    fun make_constr_def tname T n ((cname, cargs), (cname', mx)) (thy, defs, eqns, i) =
   1.228 +      let
   1.229 +        fun constr_arg dt (j, l_args, r_args) =
   1.230 +          let val T = typ_of_dtyp descr' sorts dt;
   1.231 +              val free_t = mk_Free "x" T j
   1.232 +          in (case (strip_dtyp dt, strip_type T) of
   1.233 +              ((_, DtRec m), (Us, U)) => (j + 1, free_t :: l_args, mk_lim
   1.234 +                (Const (nth all_rep_names m, U --> Univ_elT) $
   1.235 +                   app_bnds free_t (length Us)) Us :: r_args)
   1.236 +            | _ => (j + 1, free_t::l_args, (Leaf $ mk_inj T free_t)::r_args))
   1.237 +          end;
   1.238 +
   1.239 +        val (_, l_args, r_args) = fold_rev constr_arg cargs (1, [], []);
   1.240 +        val constrT = (map (typ_of_dtyp descr' sorts) cargs) ---> T;
   1.241 +        val abs_name = Sign.intern_const thy ("Abs_" ^ tname);
   1.242 +        val rep_name = Sign.intern_const thy ("Rep_" ^ tname);
   1.243 +        val lhs = list_comb (Const (cname, constrT), l_args);
   1.244 +        val rhs = mk_univ_inj r_args n i;
   1.245 +        val def = Logic.mk_equals (lhs, Const (abs_name, Univ_elT --> T) $ rhs);
   1.246 +        val def_name = Long_Name.base_name cname ^ "_def";
   1.247 +        val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
   1.248 +          (Const (rep_name, T --> Univ_elT) $ lhs, rhs));
   1.249 +        val ([def_thm], thy') =
   1.250 +          thy
   1.251 +          |> Sign.add_consts_i [(cname', constrT, mx)]
   1.252 +          |> (PureThy.add_defs false o map Thm.no_attributes) [(Binding.name def_name, def)];
   1.253 +
   1.254 +      in (thy', defs @ [def_thm], eqns @ [eqn], i + 1) end;
   1.255 +
   1.256 +    (* constructor definitions for datatype *)
   1.257 +
   1.258 +    fun dt_constr_defs ((((_, (_, _, constrs)), tname), T), constr_syntax)
   1.259 +        (thy, defs, eqns, rep_congs, dist_lemmas) =
   1.260 +      let
   1.261 +        val _ $ (_ $ (cong_f $ _) $ _) = concl_of arg_cong;
   1.262 +        val rep_const = cterm_of thy
   1.263 +          (Const (Sign.intern_const thy ("Rep_" ^ tname), T --> Univ_elT));
   1.264 +        val cong' =
   1.265 +          Drule.standard (cterm_instantiate [(cterm_of thy cong_f, rep_const)] arg_cong);
   1.266 +        val dist =
   1.267 +          Drule.standard (cterm_instantiate [(cterm_of thy distinct_f, rep_const)] distinct_lemma);
   1.268 +        val (thy', defs', eqns', _) = fold ((make_constr_def tname T) (length constrs))
   1.269 +          (constrs ~~ constr_syntax) (Sign.add_path tname thy, defs, [], 1);
   1.270 +      in
   1.271 +        (Sign.parent_path thy', defs', eqns @ [eqns'],
   1.272 +          rep_congs @ [cong'], dist_lemmas @ [dist])
   1.273 +      end;
   1.274 +
   1.275 +    val (thy4, constr_defs, constr_rep_eqns, rep_congs, dist_lemmas) =
   1.276 +      fold dt_constr_defs
   1.277 +        (hd descr ~~ new_type_names ~~ newTs ~~ constr_syntax)
   1.278 +        (thy3 |> Sign.add_consts_i iso_decls |> Sign.parent_path, [], [], [], []);
   1.279 +
   1.280 +
   1.281 +    (*********** isomorphisms for new types (introduced by typedef) ***********)
   1.282 +
   1.283 +    val _ = message config "Proving isomorphism properties ...";
   1.284 +
   1.285 +    val newT_iso_axms = map (fn (_, td) =>
   1.286 +      (collect_simp (#Abs_inverse td), #Rep_inverse td,
   1.287 +       collect_simp (#Rep td))) typedefs;
   1.288 +
   1.289 +    val newT_iso_inj_thms = map (fn (_, td) =>
   1.290 +      (collect_simp (#Abs_inject td) RS iffD1, #Rep_inject td RS iffD1)) typedefs;
   1.291 +
   1.292 +    (********* isomorphisms between existing types and "unfolded" types *******)
   1.293 +
   1.294 +    (*---------------------------------------------------------------------*)
   1.295 +    (* isomorphisms are defined using primrec-combinators:                 *)
   1.296 +    (* generate appropriate functions for instantiating primrec-combinator *)
   1.297 +    (*                                                                     *)
   1.298 +    (*   e.g.  dt_Rep_i = list_rec ... (%h t y. In1 (Scons (Leaf h) y))    *)
   1.299 +    (*                                                                     *)
   1.300 +    (* also generate characteristic equations for isomorphisms             *)
   1.301 +    (*                                                                     *)
   1.302 +    (*   e.g.  dt_Rep_i (cons h t) = In1 (Scons (dt_Rep_j h) (dt_Rep_i t)) *)
   1.303 +    (*---------------------------------------------------------------------*)
   1.304 +
   1.305 +    fun make_iso_def k ks n (cname, cargs) (fs, eqns, i) =
   1.306 +      let
   1.307 +        val argTs = map (typ_of_dtyp descr' sorts) cargs;
   1.308 +        val T = nth recTs k;
   1.309 +        val rep_name = nth all_rep_names k;
   1.310 +        val rep_const = Const (rep_name, T --> Univ_elT);
   1.311 +        val constr = Const (cname, argTs ---> T);
   1.312 +
   1.313 +        fun process_arg ks' dt (i2, i2', ts, Ts) =
   1.314 +          let
   1.315 +            val T' = typ_of_dtyp descr' sorts dt;
   1.316 +            val (Us, U) = strip_type T'
   1.317 +          in (case strip_dtyp dt of
   1.318 +              (_, DtRec j) => if j mem ks' then
   1.319 +                  (i2 + 1, i2' + 1, ts @ [mk_lim (app_bnds
   1.320 +                     (mk_Free "y" (Us ---> Univ_elT) i2') (length Us)) Us],
   1.321 +                   Ts @ [Us ---> Univ_elT])
   1.322 +                else
   1.323 +                  (i2 + 1, i2', ts @ [mk_lim
   1.324 +                     (Const (nth all_rep_names j, U --> Univ_elT) $
   1.325 +                        app_bnds (mk_Free "x" T' i2) (length Us)) Us], Ts)
   1.326 +            | _ => (i2 + 1, i2', ts @ [Leaf $ mk_inj T' (mk_Free "x" T' i2)], Ts))
   1.327 +          end;
   1.328 +
   1.329 +        val (i2, i2', ts, Ts) = fold (process_arg ks) cargs (1, 1, [], []);
   1.330 +        val xs = map (uncurry (mk_Free "x")) (argTs ~~ (1 upto (i2 - 1)));
   1.331 +        val ys = map (uncurry (mk_Free "y")) (Ts ~~ (1 upto (i2' - 1)));
   1.332 +        val f = list_abs_free (map dest_Free (xs @ ys), mk_univ_inj ts n i);
   1.333 +
   1.334 +        val (_, _, ts', _) = fold (process_arg []) cargs (1, 1, [], []);
   1.335 +        val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
   1.336 +          (rep_const $ list_comb (constr, xs), mk_univ_inj ts' n i))
   1.337 +
   1.338 +      in (fs @ [f], eqns @ [eqn], i + 1) end;
   1.339 +
   1.340 +    (* define isomorphisms for all mutually recursive datatypes in list ds *)
   1.341 +
   1.342 +    fun make_iso_defs ds (thy, char_thms) =
   1.343 +      let
   1.344 +        val ks = map fst ds;
   1.345 +        val (_, (tname, _, _)) = hd ds;
   1.346 +        val {rec_rewrites, rec_names, ...} = the (Symtab.lookup dt_info tname);
   1.347 +
   1.348 +        fun process_dt (k, (tname, _, constrs)) (fs, eqns, isos) =
   1.349 +          let
   1.350 +            val (fs', eqns', _) =
   1.351 +              fold (make_iso_def k ks (length constrs)) constrs (fs, eqns, 1);
   1.352 +            val iso = (nth recTs k, nth all_rep_names k)
   1.353 +          in (fs', eqns', isos @ [iso]) end;
   1.354 +        
   1.355 +        val (fs, eqns, isos) = fold process_dt ds ([], [], []);
   1.356 +        val fTs = map fastype_of fs;
   1.357 +        val defs = map (fn (rec_name, (T, iso_name)) => (Binding.name (Long_Name.base_name iso_name ^ "_def"),
   1.358 +          Logic.mk_equals (Const (iso_name, T --> Univ_elT),
   1.359 +            list_comb (Const (rec_name, fTs @ [T] ---> Univ_elT), fs)))) (rec_names ~~ isos);
   1.360 +        val (def_thms, thy') =
   1.361 +          apsnd Theory.checkpoint ((PureThy.add_defs false o map Thm.no_attributes) defs thy);
   1.362 +
   1.363 +        (* prove characteristic equations *)
   1.364 +
   1.365 +        val rewrites = def_thms @ (map mk_meta_eq rec_rewrites);
   1.366 +        val char_thms' = map (fn eqn => Skip_Proof.prove_global thy' [] [] eqn
   1.367 +          (fn _ => EVERY [rewrite_goals_tac rewrites, rtac refl 1])) eqns;
   1.368 +
   1.369 +      in (thy', char_thms' @ char_thms) end;
   1.370 +
   1.371 +    val (thy5, iso_char_thms) = apfst Theory.checkpoint (fold_rev make_iso_defs
   1.372 +        (tl descr) (Sign.add_path big_name thy4, []));
   1.373 +
   1.374 +    (* prove isomorphism properties *)
   1.375 +
   1.376 +    fun mk_funs_inv thy thm =
   1.377 +      let
   1.378 +        val prop = Thm.prop_of thm;
   1.379 +        val _ $ (_ $ ((S as Const (_, Type (_, [U, _]))) $ _ )) $
   1.380 +          (_ $ (_ $ (r $ (a $ _)) $ _)) = Type.legacy_freeze prop;
   1.381 +        val used = OldTerm.add_term_tfree_names (a, []);
   1.382 +
   1.383 +        fun mk_thm i =
   1.384 +          let
   1.385 +            val Ts = map (TFree o rpair HOLogic.typeS)
   1.386 +              (Name.variant_list used (replicate i "'t"));
   1.387 +            val f = Free ("f", Ts ---> U)
   1.388 +          in Skip_Proof.prove_global thy [] [] (Logic.mk_implies
   1.389 +            (HOLogic.mk_Trueprop (HOLogic.list_all
   1.390 +               (map (pair "x") Ts, S $ app_bnds f i)),
   1.391 +             HOLogic.mk_Trueprop (HOLogic.mk_eq (list_abs (map (pair "x") Ts,
   1.392 +               r $ (a $ app_bnds f i)), f))))
   1.393 +            (fn _ => EVERY [REPEAT_DETERM_N i (rtac ext 1),
   1.394 +               REPEAT (etac allE 1), rtac thm 1, atac 1])
   1.395 +          end
   1.396 +      in map (fn r => r RS subst) (thm :: map mk_thm arities) end;
   1.397 +
   1.398 +    (* prove  inj dt_Rep_i  and  dt_Rep_i x : dt_rep_set_i *)
   1.399 +
   1.400 +    val fun_congs = map (fn T => make_elim (Drule.instantiate'
   1.401 +      [SOME (ctyp_of thy5 T)] [] fun_cong)) branchTs;
   1.402 +
   1.403 +    fun prove_iso_thms ds (inj_thms, elem_thms) =
   1.404 +      let
   1.405 +        val (_, (tname, _, _)) = hd ds;
   1.406 +        val induct = (#induct o the o Symtab.lookup dt_info) tname;
   1.407 +
   1.408 +        fun mk_ind_concl (i, _) =
   1.409 +          let
   1.410 +            val T = nth recTs i;
   1.411 +            val Rep_t = Const (nth all_rep_names i, T --> Univ_elT);
   1.412 +            val rep_set_name = nth rep_set_names i
   1.413 +          in (HOLogic.all_const T $ Abs ("y", T, HOLogic.imp $
   1.414 +                HOLogic.mk_eq (Rep_t $ mk_Free "x" T i, Rep_t $ Bound 0) $
   1.415 +                  HOLogic.mk_eq (mk_Free "x" T i, Bound 0)),
   1.416 +              Const (rep_set_name, UnivT') $ (Rep_t $ mk_Free "x" T i))
   1.417 +          end;
   1.418 +
   1.419 +        val (ind_concl1, ind_concl2) = ListPair.unzip (map mk_ind_concl ds);
   1.420 +
   1.421 +        val rewrites = map mk_meta_eq iso_char_thms;
   1.422 +        val inj_thms' = map snd newT_iso_inj_thms @
   1.423 +          map (fn r => r RS @{thm injD}) inj_thms;
   1.424 +
   1.425 +        val inj_thm = Skip_Proof.prove_global thy5 [] []
   1.426 +          (HOLogic.mk_Trueprop (mk_conj ind_concl1)) (fn _ => EVERY
   1.427 +            [(indtac induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
   1.428 +             REPEAT (EVERY
   1.429 +               [rtac allI 1, rtac impI 1,
   1.430 +                exh_tac (exh_thm_of dt_info) 1,
   1.431 +                REPEAT (EVERY
   1.432 +                  [hyp_subst_tac 1,
   1.433 +                   rewrite_goals_tac rewrites,
   1.434 +                   REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
   1.435 +                   (eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1)
   1.436 +                   ORELSE (EVERY
   1.437 +                     [REPEAT (eresolve_tac (Scons_inject ::
   1.438 +                        map make_elim [Leaf_inject, Inl_inject, Inr_inject]) 1),
   1.439 +                      REPEAT (cong_tac 1), rtac refl 1,
   1.440 +                      REPEAT (atac 1 ORELSE (EVERY
   1.441 +                        [REPEAT (rtac ext 1),
   1.442 +                         REPEAT (eresolve_tac (mp :: allE ::
   1.443 +                           map make_elim (Suml_inject :: Sumr_inject ::
   1.444 +                             Lim_inject :: inj_thms') @ fun_congs) 1),
   1.445 +                         atac 1]))])])])]);
   1.446 +
   1.447 +        val inj_thms'' = map (fn r => r RS @{thm datatype_injI})
   1.448 +                             (split_conj_thm inj_thm);
   1.449 +
   1.450 +        val elem_thm = 
   1.451 +            Skip_Proof.prove_global thy5 [] [] (HOLogic.mk_Trueprop (mk_conj ind_concl2))
   1.452 +              (fn _ =>
   1.453 +               EVERY [(indtac induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
   1.454 +                rewrite_goals_tac rewrites,
   1.455 +                REPEAT ((resolve_tac rep_intrs THEN_ALL_NEW
   1.456 +                  ((REPEAT o etac allE) THEN' ares_tac elem_thms)) 1)]);
   1.457 +
   1.458 +      in (inj_thms'' @ inj_thms, elem_thms @ (split_conj_thm elem_thm))
   1.459 +      end;
   1.460 +
   1.461 +    val (iso_inj_thms_unfolded, iso_elem_thms) =
   1.462 +      fold_rev prove_iso_thms (tl descr) ([], map #3 newT_iso_axms);
   1.463 +    val iso_inj_thms = map snd newT_iso_inj_thms @
   1.464 +      map (fn r => r RS @{thm injD}) iso_inj_thms_unfolded;
   1.465 +
   1.466 +    (* prove  dt_rep_set_i x --> x : range dt_Rep_i *)
   1.467 +
   1.468 +    fun mk_iso_t (((set_name, iso_name), i), T) =
   1.469 +      let val isoT = T --> Univ_elT
   1.470 +      in HOLogic.imp $ 
   1.471 +        (Const (set_name, UnivT') $ mk_Free "x" Univ_elT i) $
   1.472 +          (if i < length newTs then HOLogic.true_const
   1.473 +           else HOLogic.mk_mem (mk_Free "x" Univ_elT i,
   1.474 +             Const (@{const_name image}, isoT --> HOLogic.mk_setT T --> UnivT) $
   1.475 +               Const (iso_name, isoT) $ Const (@{const_name UNIV}, HOLogic.mk_setT T)))
   1.476 +      end;
   1.477 +
   1.478 +    val iso_t = HOLogic.mk_Trueprop (mk_conj (map mk_iso_t
   1.479 +      (rep_set_names ~~ all_rep_names ~~ (0 upto (length descr' - 1)) ~~ recTs)));
   1.480 +
   1.481 +    (* all the theorems are proved by one single simultaneous induction *)
   1.482 +
   1.483 +    val range_eqs = map (fn r => mk_meta_eq (r RS @{thm range_ex1_eq}))
   1.484 +      iso_inj_thms_unfolded;
   1.485 +
   1.486 +    val iso_thms = if length descr = 1 then [] else
   1.487 +      drop (length newTs) (split_conj_thm
   1.488 +        (Skip_Proof.prove_global thy5 [] [] iso_t (fn _ => EVERY
   1.489 +           [(indtac rep_induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
   1.490 +            REPEAT (rtac TrueI 1),
   1.491 +            rewrite_goals_tac (mk_meta_eq choice_eq ::
   1.492 +              symmetric (mk_meta_eq @{thm expand_fun_eq}) :: range_eqs),
   1.493 +            rewrite_goals_tac (map symmetric range_eqs),
   1.494 +            REPEAT (EVERY
   1.495 +              [REPEAT (eresolve_tac ([rangeE, ex1_implies_ex RS exE] @
   1.496 +                 maps (mk_funs_inv thy5 o #1) newT_iso_axms) 1),
   1.497 +               TRY (hyp_subst_tac 1),
   1.498 +               rtac (sym RS range_eqI) 1,
   1.499 +               resolve_tac iso_char_thms 1])])));
   1.500 +
   1.501 +    val Abs_inverse_thms' =
   1.502 +      map #1 newT_iso_axms @
   1.503 +      map2 (fn r_inj => fn r => @{thm f_the_inv_into_f} OF [r_inj, r RS mp])
   1.504 +        iso_inj_thms_unfolded iso_thms;
   1.505 +
   1.506 +    val Abs_inverse_thms = maps (mk_funs_inv thy5) Abs_inverse_thms';
   1.507 +
   1.508 +    (******************* freeness theorems for constructors *******************)
   1.509 +
   1.510 +    val _ = message config "Proving freeness of constructors ...";
   1.511 +
   1.512 +    (* prove theorem  Rep_i (Constr_j ...) = Inj_j ...  *)
   1.513 +    
   1.514 +    fun prove_constr_rep_thm eqn =
   1.515 +      let
   1.516 +        val inj_thms = map fst newT_iso_inj_thms;
   1.517 +        val rewrites = @{thm o_def} :: constr_defs @ (map (mk_meta_eq o #2) newT_iso_axms)
   1.518 +      in Skip_Proof.prove_global thy5 [] [] eqn (fn _ => EVERY
   1.519 +        [resolve_tac inj_thms 1,
   1.520 +         rewrite_goals_tac rewrites,
   1.521 +         rtac refl 3,
   1.522 +         resolve_tac rep_intrs 2,
   1.523 +         REPEAT (resolve_tac iso_elem_thms 1)])
   1.524 +      end;
   1.525 +
   1.526 +    (*--------------------------------------------------------------*)
   1.527 +    (* constr_rep_thms and rep_congs are used to prove distinctness *)
   1.528 +    (* of constructors.                                             *)
   1.529 +    (*--------------------------------------------------------------*)
   1.530 +
   1.531 +    val constr_rep_thms = map (map prove_constr_rep_thm) constr_rep_eqns;
   1.532 +
   1.533 +    val dist_rewrites = map (fn (rep_thms, dist_lemma) =>
   1.534 +      dist_lemma::(rep_thms @ [In0_eq, In1_eq, In0_not_In1, In1_not_In0]))
   1.535 +        (constr_rep_thms ~~ dist_lemmas);
   1.536 +
   1.537 +    fun prove_distinct_thms dist_rewrites' (k, ts) =
   1.538 +      let
   1.539 +        fun prove [] = []
   1.540 +          | prove (t :: ts) =
   1.541 +              let
   1.542 +                val dist_thm = Skip_Proof.prove_global thy5 [] [] t (fn _ =>
   1.543 +                  EVERY [simp_tac (HOL_ss addsimps dist_rewrites') 1])
   1.544 +              in dist_thm :: Drule.standard (dist_thm RS not_sym) :: prove ts end;
   1.545 +      in prove ts end;
   1.546 +
   1.547 +    val distinct_thms = map2 (prove_distinct_thms)
   1.548 +      dist_rewrites (Datatype_Prop.make_distincts descr sorts);
   1.549 +
   1.550 +    (* prove injectivity of constructors *)
   1.551 +
   1.552 +    fun prove_constr_inj_thm rep_thms t =
   1.553 +      let val inj_thms = Scons_inject :: (map make_elim
   1.554 +        (iso_inj_thms @
   1.555 +          [In0_inject, In1_inject, Leaf_inject, Inl_inject, Inr_inject,
   1.556 +           Lim_inject, Suml_inject, Sumr_inject]))
   1.557 +      in Skip_Proof.prove_global thy5 [] [] t (fn _ => EVERY
   1.558 +        [rtac iffI 1,
   1.559 +         REPEAT (etac conjE 2), hyp_subst_tac 2, rtac refl 2,
   1.560 +         dresolve_tac rep_congs 1, dtac box_equals 1,
   1.561 +         REPEAT (resolve_tac rep_thms 1),
   1.562 +         REPEAT (eresolve_tac inj_thms 1),
   1.563 +         REPEAT (ares_tac [conjI] 1 ORELSE (EVERY [REPEAT (rtac ext 1),
   1.564 +           REPEAT (eresolve_tac (make_elim fun_cong :: inj_thms) 1),
   1.565 +           atac 1]))])
   1.566 +      end;
   1.567 +
   1.568 +    val constr_inject = map (fn (ts, thms) => map (prove_constr_inj_thm thms) ts)
   1.569 +      ((Datatype_Prop.make_injs descr sorts) ~~ constr_rep_thms);
   1.570 +
   1.571 +    val ((constr_inject', distinct_thms'), thy6) =
   1.572 +      thy5
   1.573 +      |> Sign.parent_path
   1.574 +      |> store_thmss "inject" new_type_names constr_inject
   1.575 +      ||>> store_thmss "distinct" new_type_names distinct_thms;
   1.576 +
   1.577 +    (*************************** induction theorem ****************************)
   1.578 +
   1.579 +    val _ = message config "Proving induction rule for datatypes ...";
   1.580 +
   1.581 +    val Rep_inverse_thms = (map (fn (_, iso, _) => iso RS subst) newT_iso_axms) @
   1.582 +      (map (fn r => r RS @{thm the_inv_f_f} RS subst) iso_inj_thms_unfolded);
   1.583 +    val Rep_inverse_thms' = map (fn r => r RS @{thm the_inv_f_f}) iso_inj_thms_unfolded;
   1.584 +
   1.585 +    fun mk_indrule_lemma ((i, _), T) (prems, concls) =
   1.586 +      let
   1.587 +        val Rep_t = Const (nth all_rep_names i, T --> Univ_elT) $
   1.588 +          mk_Free "x" T i;
   1.589 +
   1.590 +        val Abs_t = if i < length newTs then
   1.591 +            Const (Sign.intern_const thy6
   1.592 +              ("Abs_" ^ (nth new_type_names i)), Univ_elT --> T)
   1.593 +          else Const (@{const_name the_inv_into},
   1.594 +              [HOLogic.mk_setT T, T --> Univ_elT, Univ_elT] ---> T) $
   1.595 +            HOLogic.mk_UNIV T $ Const (nth all_rep_names i, T --> Univ_elT)
   1.596 +
   1.597 +      in (prems @ [HOLogic.imp $
   1.598 +            (Const (nth rep_set_names i, UnivT') $ Rep_t) $
   1.599 +              (mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ (Abs_t $ Rep_t))],
   1.600 +          concls @ [mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ mk_Free "x" T i])
   1.601 +      end;
   1.602 +
   1.603 +    val (indrule_lemma_prems, indrule_lemma_concls) =
   1.604 +      fold mk_indrule_lemma (descr' ~~ recTs) ([], []);
   1.605 +
   1.606 +    val cert = cterm_of thy6;
   1.607 +
   1.608 +    val indrule_lemma = Skip_Proof.prove_global thy6 [] []
   1.609 +      (Logic.mk_implies
   1.610 +        (HOLogic.mk_Trueprop (mk_conj indrule_lemma_prems),
   1.611 +         HOLogic.mk_Trueprop (mk_conj indrule_lemma_concls))) (fn _ => EVERY
   1.612 +           [REPEAT (etac conjE 1),
   1.613 +            REPEAT (EVERY
   1.614 +              [TRY (rtac conjI 1), resolve_tac Rep_inverse_thms 1,
   1.615 +               etac mp 1, resolve_tac iso_elem_thms 1])]);
   1.616 +
   1.617 +    val Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule_lemma)));
   1.618 +    val frees = if length Ps = 1 then [Free ("P", snd (dest_Var (hd Ps)))] else
   1.619 +      map (Free o apfst fst o dest_Var) Ps;
   1.620 +    val indrule_lemma' = cterm_instantiate (map cert Ps ~~ map cert frees) indrule_lemma;
   1.621 +
   1.622 +    val dt_induct_prop = Datatype_Prop.make_ind descr sorts;
   1.623 +    val dt_induct = Skip_Proof.prove_global thy6 []
   1.624 +      (Logic.strip_imp_prems dt_induct_prop) (Logic.strip_imp_concl dt_induct_prop)
   1.625 +      (fn {prems, ...} => EVERY
   1.626 +        [rtac indrule_lemma' 1,
   1.627 +         (indtac rep_induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
   1.628 +         EVERY (map (fn (prem, r) => (EVERY
   1.629 +           [REPEAT (eresolve_tac Abs_inverse_thms 1),
   1.630 +            simp_tac (HOL_basic_ss addsimps ((symmetric r)::Rep_inverse_thms')) 1,
   1.631 +            DEPTH_SOLVE_1 (ares_tac [prem] 1 ORELSE etac allE 1)]))
   1.632 +                (prems ~~ (constr_defs @ (map mk_meta_eq iso_char_thms))))]);
   1.633 +
   1.634 +    val ([dt_induct'], thy7) =
   1.635 +      thy6
   1.636 +      |> Sign.add_path big_name
   1.637 +      |> PureThy.add_thms [((Binding.name "induct", dt_induct), [case_names_induct])]
   1.638 +      ||> Sign.parent_path
   1.639 +      ||> Theory.checkpoint;
   1.640 +
   1.641 +  in
   1.642 +    ((constr_inject', distinct_thms', dt_induct'), thy7)
   1.643 +  end;
   1.644 +
   1.645 +
   1.646 +
   1.647 +(** definitional introduction of datatypes **)
   1.648 +
   1.649 +fun gen_add_datatype prep_typ config new_type_names dts thy =
   1.650 +  let
   1.651 +    val _ = Theory.requires thy "Datatype" "datatype definitions";
   1.652 +
   1.653 +    (* this theory is used just for parsing *)
   1.654 +    val tmp_thy = thy |>
   1.655 +      Theory.copy |>
   1.656 +      Sign.add_types (map (fn (tvs, tname, mx, _) =>
   1.657 +        (tname, length tvs, mx)) dts);
   1.658 +
   1.659 +    val (tyvars, _, _, _)::_ = dts;
   1.660 +    val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
   1.661 +      let val full_tname = Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname)
   1.662 +      in
   1.663 +        (case duplicates (op =) tvs of
   1.664 +          [] =>
   1.665 +            if eq_set (op =) (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
   1.666 +            else error ("Mutually recursive datatypes must have same type parameters")
   1.667 +        | dups => error ("Duplicate parameter(s) for datatype " ^ quote (Binding.str_of tname) ^
   1.668 +            " : " ^ commas dups))
   1.669 +      end) dts);
   1.670 +    val dt_names = map fst new_dts;
   1.671 +
   1.672 +    val _ =
   1.673 +      (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
   1.674 +        [] => ()
   1.675 +      | dups => error ("Duplicate datatypes: " ^ commas dups));
   1.676 +
   1.677 +    fun prep_dt_spec (tvs, tname, mx, constrs) tname' (dts', constr_syntax, sorts, i) =
   1.678 +      let
   1.679 +        fun prep_constr (cname, cargs, mx') (constrs, constr_syntax', sorts') =
   1.680 +          let
   1.681 +            val (cargs', sorts'') = fold_map (prep_typ tmp_thy) cargs sorts';
   1.682 +            val _ =
   1.683 +              (case subtract (op =) tvs (fold (curry OldTerm.add_typ_tfree_names) cargs' []) of
   1.684 +                [] => ()
   1.685 +              | vs => error ("Extra type variables on rhs: " ^ commas vs))
   1.686 +          in (constrs @ [(Sign.full_name_path tmp_thy tname'
   1.687 +                  (Binding.map_name (Syntax.const_name mx') cname),
   1.688 +                   map (dtyp_of_typ new_dts) cargs')],
   1.689 +              constr_syntax' @ [(cname, mx')], sorts'')
   1.690 +          end handle ERROR msg => cat_error msg
   1.691 +           ("The error above occured in constructor " ^ quote (Binding.str_of cname) ^
   1.692 +            " of datatype " ^ quote (Binding.str_of tname));
   1.693 +
   1.694 +        val (constrs', constr_syntax', sorts') =
   1.695 +          fold prep_constr constrs ([], [], sorts)
   1.696 +
   1.697 +      in
   1.698 +        case duplicates (op =) (map fst constrs') of
   1.699 +           [] =>
   1.700 +             (dts' @ [(i, (Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname),
   1.701 +                map DtTFree tvs, constrs'))],
   1.702 +              constr_syntax @ [constr_syntax'], sorts', i + 1)
   1.703 +         | dups => error ("Duplicate constructors " ^ commas dups ^
   1.704 +             " in datatype " ^ quote (Binding.str_of tname))
   1.705 +      end;
   1.706 +
   1.707 +    val (dts', constr_syntax, sorts', i) =
   1.708 +      fold2 prep_dt_spec dts new_type_names ([], [], [], 0);
   1.709 +    val sorts = sorts' @ map (rpair (Sign.defaultS tmp_thy)) (subtract (op =) (map fst sorts') tyvars);
   1.710 +    val dt_info = Datatype_Data.get_all thy;
   1.711 +    val (descr, _) = unfold_datatypes tmp_thy dts' sorts dt_info dts' i;
   1.712 +    val _ = check_nonempty descr handle (exn as Datatype_Empty s) =>
   1.713 +      if #strict config then error ("Nonemptiness check failed for datatype " ^ s)
   1.714 +      else raise exn;
   1.715 +
   1.716 +    val _ = message config ("Constructing datatype(s) " ^ commas_quote new_type_names);
   1.717 +
   1.718 +  in
   1.719 +    thy
   1.720 +    |> representation_proofs config dt_info new_type_names descr sorts
   1.721 +        types_syntax constr_syntax (Datatype_Data.mk_case_names_induct (flat descr))
   1.722 +    |-> (fn (inject, distinct, induct) => Datatype_Data.derive_datatype_props
   1.723 +        config dt_names (SOME new_type_names) descr sorts
   1.724 +        induct inject distinct)
   1.725 +  end;
   1.726 +
   1.727 +val add_datatype = gen_add_datatype Datatype_Data.cert_typ;
   1.728 +val datatype_cmd = snd ooo gen_add_datatype Datatype_Data.read_typ default_config;
   1.729 +
   1.730 +local
   1.731 +
   1.732 +structure P = OuterParse and K = OuterKeyword
   1.733 +
   1.734 +fun prep_datatype_decls args =
   1.735 +  let
   1.736 +    val names = map
   1.737 +      (fn ((((NONE, _), t), _), _) => Binding.name_of t | ((((SOME t, _), _), _), _) => t) args;
   1.738 +    val specs = map (fn ((((_, vs), t), mx), cons) =>
   1.739 +      (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
   1.740 +  in (names, specs) end;
   1.741 +
   1.742 +val parse_datatype_decl =
   1.743 +  (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.binding -- P.opt_infix --
   1.744 +    (P.$$$ "=" |-- P.enum1 "|" (P.binding -- Scan.repeat P.typ -- P.opt_mixfix)));
   1.745 +
   1.746 +val parse_datatype_decls = P.and_list1 parse_datatype_decl >> prep_datatype_decls;
   1.747 +
   1.748 +in
   1.749 +
   1.750 +val _ =
   1.751 +  OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
   1.752 +    (parse_datatype_decls >> (fn (names, specs) => Toplevel.theory (datatype_cmd names specs)));
   1.753  
   1.754  end;
   1.755 +
   1.756 +end;