src/HOL/Tools/datatype_package.ML
author wenzelm
Tue Feb 22 21:48:50 2000 +0100 (2000-02-22)
changeset 8279 3453f73fad71
parent 8100 6186ee807f2e
child 8306 9855f1801d2b
permissions -rw-r--r--
added cases_tac;
     1 (*  Title:      HOL/Tools/datatype_package.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer
     4     Copyright   1998  TU Muenchen
     5 
     6 Datatype package for Isabelle/HOL.
     7 *)
     8 
     9 signature BASIC_DATATYPE_PACKAGE =
    10 sig
    11   val induct_tac : string -> int -> tactic
    12   val exhaust_tac : string -> int -> tactic
    13   val cases_tac : string -> int -> tactic
    14   val distinct_simproc : simproc
    15 end;
    16 
    17 signature DATATYPE_PACKAGE =
    18 sig
    19   include BASIC_DATATYPE_PACKAGE
    20   val quiet_mode : bool ref
    21   val add_datatype : bool -> string list -> (string list * bstring * mixfix *
    22     (bstring * string list * mixfix) list) list -> theory -> theory *
    23       {distinct : thm list list,
    24        inject : thm list list,
    25        exhaustion : thm list,
    26        rec_thms : thm list,
    27        case_thms : thm list list,
    28        split_thms : (thm * thm) list,
    29        induction : thm,
    30        size : thm list,
    31        simps : thm list}
    32   val add_datatype_i : bool -> string list -> (string list * bstring * mixfix *
    33     (bstring * typ list * mixfix) list) list -> theory -> theory *
    34       {distinct : thm list list,
    35        inject : thm list list,
    36        exhaustion : thm list,
    37        rec_thms : thm list,
    38        case_thms : thm list list,
    39        split_thms : (thm * thm) list,
    40        induction : thm,
    41        size : thm list,
    42        simps : thm list}
    43   val rep_datatype_i : string list option -> (thm * theory attribute list) list list ->
    44     (thm * theory attribute list) list list -> (thm * theory attribute list) -> theory -> theory *
    45       {distinct : thm list list,
    46        inject : thm list list,
    47        exhaustion : thm list,
    48        rec_thms : thm list,
    49        case_thms : thm list list,
    50        split_thms : (thm * thm) list,
    51        induction : thm,
    52        size : thm list,
    53        simps : thm list}
    54   val rep_datatype : string list option -> (xstring * Args.src list) list list ->
    55     (xstring * Args.src list) list list -> xstring * Args.src list -> theory -> theory *
    56       {distinct : thm list list,
    57        inject : thm list list,
    58        exhaustion : thm list,
    59        rec_thms : thm list,
    60        case_thms : thm list list,
    61        split_thms : (thm * thm) list,
    62        induction : thm,
    63        size : thm list,
    64        simps : thm list}
    65   val get_datatypes : theory -> DatatypeAux.datatype_info Symtab.table
    66   val print_datatypes : theory -> unit
    67   val datatype_info_sg : Sign.sg -> string -> DatatypeAux.datatype_info option
    68   val datatype_info : theory -> string -> DatatypeAux.datatype_info option
    69   val datatype_info_sg_err : Sign.sg -> string -> DatatypeAux.datatype_info
    70   val datatype_info_err : theory -> string -> DatatypeAux.datatype_info
    71   val constrs_of : theory -> string -> term list option
    72   val constrs_of_sg : Sign.sg -> string -> term list option
    73   val case_const_of : theory -> string -> term option
    74   val cases_of: Sign.sg -> string -> thm
    75   val setup: (theory -> theory) list
    76 end;
    77 
    78 structure DatatypePackage : DATATYPE_PACKAGE =
    79 struct
    80 
    81 open DatatypeAux;
    82 
    83 val quiet_mode = quiet_mode;
    84 
    85 
    86 (* data kind 'HOL/datatypes' *)
    87 
    88 structure DatatypesArgs =
    89 struct
    90   val name = "HOL/datatypes";
    91   type T = datatype_info Symtab.table;
    92 
    93   val empty = Symtab.empty;
    94   val copy = I;
    95   val prep_ext = I;
    96   val merge: T * T -> T = Symtab.merge (K true);
    97 
    98   fun print sg tab =
    99     Pretty.writeln (Pretty.strs ("datatypes:" ::
   100       map #1 (Sign.cond_extern_table sg Sign.typeK tab)));
   101 end;
   102 
   103 structure DatatypesData = TheoryDataFun(DatatypesArgs);
   104 val get_datatypes_sg = DatatypesData.get_sg;
   105 val get_datatypes = DatatypesData.get;
   106 val put_datatypes = DatatypesData.put;
   107 val print_datatypes = DatatypesData.print;
   108 
   109 
   110 (** theory information about datatypes **)
   111 
   112 fun datatype_info_sg sg name = Symtab.lookup (get_datatypes_sg sg, name);
   113 
   114 fun datatype_info_sg_err sg name = (case datatype_info_sg sg name of
   115       Some info => info
   116     | None => error ("Unknown datatype " ^ quote name));
   117 
   118 val datatype_info = datatype_info_sg o Theory.sign_of;
   119 
   120 fun datatype_info_err thy name = (case datatype_info thy name of
   121       Some info => info
   122     | None => error ("Unknown datatype " ^ quote name));
   123 
   124 fun constrs_of_sg sg tname = (case datatype_info_sg sg tname of
   125    Some {index, descr, ...} =>
   126      let val (_, _, constrs) = the (assoc (descr, index))
   127      in Some (map (fn (cname, _) => Const (cname, the (Sign.const_type sg cname))) constrs)
   128      end
   129  | _ => None);
   130 
   131 val constrs_of = constrs_of_sg o Theory.sign_of;
   132 
   133 val exhaustion_of = #exhaustion oo datatype_info_sg_err
   134 fun cases_of sg name = if name = HOLogic.boolN then case_split_thm else exhaustion_of sg name;
   135 
   136 fun case_const_of thy tname = (case datatype_info thy tname of
   137    Some {case_name, ...} => Some (Const (case_name, the (Sign.const_type
   138      (Theory.sign_of thy) case_name)))
   139  | _ => None);
   140 
   141 fun find_tname var Bi =
   142   let val frees = map dest_Free (term_frees Bi)
   143       val params = Logic.strip_params Bi;
   144   in case assoc (frees @ params, var) of
   145        None => error ("No such variable in subgoal: " ^ quote var)
   146      | Some(Type (tn, _)) => tn
   147      | _ => error ("Cannot determine type of " ^ quote var)
   148   end;
   149 
   150 fun infer_tname state i aterm =
   151   let
   152     val sign = Thm.sign_of_thm state;
   153     val (_, _, Bi, _) = Thm.dest_state (state, i)
   154     val params = Logic.strip_params Bi;   (*params of subgoal i*)
   155     val params = rev (rename_wrt_term Bi params);   (*as they are printed*)
   156     val (types, sorts) = types_sorts state;
   157     fun types' (a, ~1) = (case assoc (params, a) of None => types(a, ~1) | sm => sm)
   158       | types' ixn = types ixn;
   159     val (ct, _) = read_def_cterm (sign, types', sorts) [] false (aterm, TypeInfer.logicT);
   160   in case #T (rep_cterm ct) of
   161        Type (tn, _) => tn
   162      | _ => error ("Cannot determine type of " ^ quote aterm)
   163   end;
   164 
   165 (*Warn if the (induction) variable occurs Free among the premises, which
   166   usually signals a mistake.  But calls the tactic either way!*)
   167 fun occs_in_prems tacf vars = 
   168   SUBGOAL (fn (Bi, i) =>
   169 	   (if  exists (fn Free (a, _) => a mem vars)
   170 	              (foldr add_term_frees (#2 (strip_context Bi), []))
   171 	     then warning "Induction variable occurs also among premises!"
   172 	     else ();
   173 	    tacf i));
   174 
   175 (* generic induction tactic for datatypes *)
   176 
   177 fun induct_tac s i state =
   178   let
   179     val vars = Syntax.read_idents s;
   180     val (_, _, Bi, _) = dest_state (state, i);
   181     val {sign, ...} = rep_thm state;
   182     val tn = find_tname (hd vars) Bi;
   183     val {induction, ...} = datatype_info_sg_err sign tn;
   184     val ind_vnames = map (fn (_ $ Var (ixn, _)) =>
   185       implode (tl (explode (Syntax.string_of_vname ixn))))
   186         (dest_conj (HOLogic.dest_Trueprop (concl_of induction)));
   187     val insts = (ind_vnames ~~ vars) handle LIST _ =>
   188       error ("Induction rule for type " ^ tn ^ " has different number of variables")
   189   in
   190     occs_in_prems (res_inst_tac insts induction) vars i state
   191   end;
   192 
   193 
   194 (* generic exhaustion tactic for datatypes *)
   195 
   196 fun gen_exhaust_tac get_rule aterm i state =
   197   let
   198     val rule = get_rule (Thm.sign_of_thm state) (infer_tname state i aterm);
   199     val _ $ Var (ixn, _) $ _ = HOLogic.dest_Trueprop
   200       (hd (Logic.strip_assums_hyp (hd (Thm.prems_of rule))));
   201     val exh_vname = implode (tl (explode (Syntax.string_of_vname ixn)))
   202   in res_inst_tac [(exh_vname, aterm)] rule i state end;
   203 
   204 val exhaust_tac = gen_exhaust_tac exhaustion_of;
   205 val cases_tac = gen_exhaust_tac cases_of;
   206 
   207 
   208 
   209 (**** simplification procedure for showing distinctness of constructors ****)
   210 
   211 fun stripT (i, Type ("fun", [_, T])) = stripT (i + 1, T)
   212   | stripT p = p;
   213 
   214 fun stripC (i, f $ x) = stripC (i + 1, f)
   215   | stripC p = p;
   216 
   217 val distinctN = "constr_distinct";
   218 
   219 exception ConstrDistinct of term;
   220 
   221 fun distinct_proc sg _ (t as Const ("op =", _) $ t1 $ t2) =
   222   (case (stripC (0, t1), stripC (0, t2)) of
   223      ((i, Const (cname1, T1)), (j, Const (cname2, T2))) =>
   224          (case (stripT (0, T1), stripT (0, T2)) of
   225             ((i', Type (tname1, _)), (j', Type (tname2, _))) =>
   226                 if tname1 = tname2 andalso not (cname1 = cname2) andalso i = i' andalso j = j' then
   227                    (case (constrs_of_sg sg tname1) of
   228                       Some constrs => let val cnames = map (fst o dest_Const) constrs
   229                         in if cname1 mem cnames andalso cname2 mem cnames then
   230                              let val eq_t = Logic.mk_equals (t, Const ("False", HOLogic.boolT));
   231                                  val eq_ct = cterm_of sg eq_t;
   232                                  val Datatype_thy = theory "Datatype";
   233                                  val [In0_inject, In1_inject, In0_not_In1, In1_not_In0] =
   234                                    map (get_thm Datatype_thy)
   235                                      ["In0_inject", "In1_inject", "In0_not_In1", "In1_not_In0"]
   236                              in (case (#distinct (datatype_info_sg_err sg tname1)) of
   237                                  QuickAndDirty => Some (Thm.invoke_oracle
   238                                    Datatype_thy distinctN (sg, ConstrDistinct eq_t))
   239                                | FewConstrs thms => Some (prove_goalw_cterm [] eq_ct (K
   240                                    [rtac eq_reflection 1, rtac iffI 1, rtac notE 1,
   241                                     atac 2, resolve_tac thms 1, etac FalseE 1]))
   242                                | ManyConstrs (thm, ss) => Some (prove_goalw_cterm [] eq_ct (K
   243                                    [rtac eq_reflection 1, rtac iffI 1, dtac thm 1,
   244                                     full_simp_tac ss 1,
   245                                     REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
   246                                     eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1,
   247                                     etac FalseE 1])))
   248                              end
   249                            else None
   250                         end
   251                     | None => None)
   252                 else None
   253           | _ => None)
   254    | _ => None)
   255   | distinct_proc sg _ _ = None;
   256 
   257 val distinct_pats = [Thm.read_cterm (Theory.sign_of HOL.thy) ("s = t", HOLogic.termT)];
   258 val distinct_simproc = mk_simproc distinctN distinct_pats distinct_proc;
   259 
   260 val dist_ss = HOL_ss addsimprocs [distinct_simproc];
   261 
   262 val simproc_setup =
   263   [Theory.add_oracle (distinctN, fn (_, ConstrDistinct t) => t),
   264    fn thy => (simpset_ref_of thy := simpset_of thy addsimprocs [distinct_simproc]; thy)];
   265 
   266 
   267 (* prepare types *)
   268 
   269 fun read_typ sign ((Ts, sorts), str) =
   270   let
   271     val T = Type.no_tvars (Sign.read_typ (sign, (curry assoc)
   272       (map (apfst (rpair ~1)) sorts)) str) handle TYPE (msg, _, _) => error msg
   273   in (Ts @ [T], add_typ_tfrees (T, sorts)) end;
   274 
   275 fun cert_typ sign ((Ts, sorts), raw_T) =
   276   let
   277     val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle
   278       TYPE (msg, _, _) => error msg;
   279     val sorts' = add_typ_tfrees (T, sorts)
   280   in (Ts @ [T],
   281       case duplicates (map fst sorts') of
   282          [] => sorts'
   283        | dups => error ("Inconsistent sort constraints for " ^ commas dups))
   284   end;
   285 
   286 
   287 (**** make datatype info ****)
   288 
   289 fun make_dt_info descr induct reccomb_names rec_thms
   290   ((((((((i, (_, (tname, _, _))), case_name), case_thms),
   291     exhaustion_thm), distinct_thm), inject), nchotomy), case_cong) = (tname,
   292       {index = i,
   293        descr = descr,
   294        rec_names = reccomb_names,
   295        rec_rewrites = rec_thms,
   296        case_name = case_name,
   297        case_rewrites = case_thms,
   298        induction = induct,
   299        exhaustion = exhaustion_thm,
   300        distinct = distinct_thm,
   301        inject = inject,
   302        nchotomy = nchotomy,
   303        case_cong = case_cong});
   304 
   305 fun store_clasimp thy (cla, simp) =
   306   (claset_ref_of thy := cla; simpset_ref_of thy := simp);
   307 
   308 
   309 (********************* axiomatic introduction of datatypes ********************)
   310 
   311 fun add_and_get_axioms label tnames ts thy =
   312   foldr (fn ((tname, t), (thy', axs)) =>
   313     let
   314       val thy'' = thy' |>
   315         Theory.add_path tname |>
   316         PureThy.add_axioms_i [((label, t), [])];
   317       val ax = PureThy.get_thm thy'' label
   318     in (Theory.parent_path thy'', ax::axs)
   319     end) (tnames ~~ ts, (thy, []));
   320 
   321 fun add_and_get_axiomss label tnames tss thy =
   322   foldr (fn ((tname, ts), (thy', axss)) =>
   323     let
   324       val thy'' = thy' |>
   325         Theory.add_path tname |>
   326         PureThy.add_axiomss_i [((label, ts), [])];
   327       val axs = PureThy.get_thms thy'' label
   328     in (Theory.parent_path thy'', axs::axss)
   329     end) (tnames ~~ tss, (thy, []));
   330 
   331 fun add_datatype_axm flat_names new_type_names descr sorts types_syntax constr_syntax dt_info thy =
   332   let
   333     val descr' = flat descr;
   334     val recTs = get_rec_types descr' sorts;
   335     val used = foldr add_typ_tfree_names (recTs, []);
   336     val newTs = take (length (hd descr), recTs);
   337 
   338     val no_size = exists (fn (_, (_, _, constrs)) => exists (fn (_, cargs) => exists
   339       (fn (DtType ("fun", [_, DtRec _])) => true | _ => false) cargs) constrs) descr';
   340 
   341     (**** declare new types and constants ****)
   342 
   343     val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
   344 
   345     val constr_decls = map (fn (((_, (_, _, constrs)), T), constr_syntax') =>
   346       map (fn ((_, cargs), (cname, mx)) =>
   347         (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
   348           (constrs ~~ constr_syntax')) ((hd descr) ~~ newTs ~~ constr_syntax);
   349 
   350     val rec_result_Ts = map TFree (variantlist (replicate (length descr') "'t", used) ~~
   351       replicate (length descr') HOLogic.termS);
   352 
   353     val reccomb_fn_Ts = flat (map (fn (i, (_, _, constrs)) =>
   354       map (fn (_, cargs) =>
   355         let
   356           val Ts = map (typ_of_dtyp descr' sorts) cargs;
   357           val recs = filter (is_rec_type o fst) (cargs ~~ Ts);
   358 
   359           fun mk_argT (DtRec k, _) = nth_elem (k, rec_result_Ts)
   360             | mk_argT (DtType ("fun", [_, DtRec k]), Type ("fun", [T, _])) =
   361                T --> nth_elem (k, rec_result_Ts);
   362 
   363           val argTs = Ts @ map mk_argT recs
   364         in argTs ---> nth_elem (i, rec_result_Ts)
   365         end) constrs) descr');
   366 
   367     val big_reccomb_name = (space_implode "_" new_type_names) ^ "_rec";
   368     val reccomb_names = if length descr' = 1 then [big_reccomb_name] else
   369       (map ((curry (op ^) (big_reccomb_name ^ "_")) o string_of_int)
   370         (1 upto (length descr')));
   371 
   372     val big_size_name = space_implode "_" new_type_names ^ "_size";
   373     val size_names = if length (flat (tl descr)) = 1 then [big_size_name] else
   374       map (fn i => big_size_name ^ "_" ^ string_of_int i)
   375         (1 upto length (flat (tl descr)));
   376 
   377     val freeT = TFree (variant used "'t", HOLogic.termS);
   378     val case_fn_Ts = map (fn (i, (_, _, constrs)) =>
   379       map (fn (_, cargs) =>
   380         let val Ts = map (typ_of_dtyp descr' sorts) cargs
   381         in Ts ---> freeT end) constrs) (hd descr);
   382 
   383     val case_names = map (fn s => (s ^ "_case")) new_type_names;
   384 
   385     val thy2' = thy |>
   386 
   387       (** new types **)
   388 
   389       curry (foldr (fn (((name, mx), tvs), thy') => thy' |>
   390           TypedefPackage.add_typedecls [(name, tvs, mx)]))
   391         (types_syntax ~~ tyvars) |>
   392       add_path flat_names (space_implode "_" new_type_names) |>
   393 
   394       (** primrec combinators **)
   395 
   396       Theory.add_consts_i (map (fn ((name, T), T') =>
   397         (name, reccomb_fn_Ts @ [T] ---> T', NoSyn))
   398           (reccomb_names ~~ recTs ~~ rec_result_Ts)) |>
   399 
   400       (** case combinators **)
   401 
   402       Theory.add_consts_i (map (fn ((name, T), Ts) =>
   403         (name, Ts @ [T] ---> freeT, NoSyn))
   404           (case_names ~~ newTs ~~ case_fn_Ts)) |>
   405       Theory.add_trrules_i (DatatypeProp.make_case_trrules new_type_names descr);
   406 
   407     val reccomb_names' = map (Sign.intern_const (Theory.sign_of thy2')) reccomb_names;
   408     val case_names' = map (Sign.intern_const (Theory.sign_of thy2')) case_names;
   409 
   410     val thy2 = thy2' |>
   411 
   412       (** size functions **)
   413 
   414       (if no_size then I else Theory.add_consts_i (map (fn (s, T) =>
   415         (Sign.base_name s, T --> HOLogic.natT, NoSyn))
   416           (size_names ~~ drop (length (hd descr), recTs)))) |>
   417 
   418       (** constructors **)
   419 
   420       parent_path flat_names |>
   421       curry (foldr (fn (((((_, (_, _, constrs)), T), tname),
   422         constr_syntax'), thy') => thy' |>
   423           add_path flat_names tname |>
   424             Theory.add_consts_i (map (fn ((_, cargs), (cname, mx)) =>
   425               (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
   426                 (constrs ~~ constr_syntax')) |>
   427           parent_path flat_names))
   428             (hd descr ~~ newTs ~~ new_type_names ~~ constr_syntax);
   429 
   430     (**** introduction of axioms ****)
   431 
   432     val rec_axs = DatatypeProp.make_primrecs new_type_names descr sorts thy2;
   433     val size_axs = if no_size then [] else DatatypeProp.make_size new_type_names descr sorts thy2;
   434 
   435     val (thy3, inject) = thy2 |>
   436       Theory.add_path (space_implode "_" new_type_names) |>
   437       PureThy.add_axioms_i [(("induct", DatatypeProp.make_ind descr sorts), [])] |>
   438       PureThy.add_axiomss_i [(("recs", rec_axs), [])] |>
   439       (if no_size then I else PureThy.add_axiomss_i [(("size", size_axs), [])]) |>
   440       Theory.parent_path |>
   441       add_and_get_axiomss "inject" new_type_names
   442         (DatatypeProp.make_injs descr sorts);
   443     val induct = get_thm thy3 "induct";
   444     val rec_thms = get_thms thy3 "recs";
   445     val size_thms = if no_size then [] else get_thms thy3 "size";
   446     val (thy4, distinct) = add_and_get_axiomss "distinct" new_type_names
   447       (DatatypeProp.make_distincts new_type_names descr sorts thy3) thy3;
   448     val (thy5, exhaustion) = add_and_get_axioms "exhaust" new_type_names
   449       (DatatypeProp.make_casedists descr sorts) thy4;
   450     val (thy6, case_thms) = add_and_get_axiomss "cases" new_type_names
   451       (DatatypeProp.make_cases new_type_names descr sorts thy5) thy5;
   452     val (split_ts, split_asm_ts) = ListPair.unzip
   453       (DatatypeProp.make_splits new_type_names descr sorts thy6);
   454     val (thy7, split) = add_and_get_axioms "split" new_type_names split_ts thy6;
   455     val (thy8, split_asm) = add_and_get_axioms "split_asm" new_type_names
   456       split_asm_ts thy7;
   457     val (thy9, nchotomys) = add_and_get_axioms "nchotomy" new_type_names
   458       (DatatypeProp.make_nchotomys descr sorts) thy8;
   459     val (thy10, case_congs) = add_and_get_axioms "case_cong" new_type_names
   460       (DatatypeProp.make_case_congs new_type_names descr sorts thy9) thy9;
   461     
   462     val dt_infos = map (make_dt_info descr' induct reccomb_names' rec_thms)
   463       ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names' ~~ case_thms ~~
   464         exhaustion ~~ replicate (length (hd descr)) QuickAndDirty ~~ inject ~~
   465           nchotomys ~~ case_congs);
   466 
   467     val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   468 
   469     val thy11 = thy10 |>
   470       Theory.add_path (space_implode "_" new_type_names) |>
   471       PureThy.add_thmss [(("simps", simps), [])] |>
   472       put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
   473       Theory.parent_path;
   474 
   475     val _ = store_clasimp thy11 ((claset_of thy11, simpset_of thy11)
   476       addsimps2 flat case_thms addsimps2 size_thms addsimps2 rec_thms
   477       addIffs flat (inject @ distinct));
   478 
   479   in
   480     (thy11,
   481      {distinct = distinct,
   482       inject = inject,
   483       exhaustion = exhaustion,
   484       rec_thms = rec_thms,
   485       case_thms = case_thms,
   486       split_thms = split ~~ split_asm,
   487       induction = induct,
   488       size = size_thms,
   489       simps = simps})
   490   end;
   491 
   492 
   493 (******************* definitional introduction of datatypes *******************)
   494 
   495 fun add_datatype_def flat_names new_type_names descr sorts types_syntax constr_syntax dt_info thy =
   496   let
   497     val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
   498 
   499     val (thy2, inject, distinct, dist_rewrites, simproc_dists, induct) = thy |>
   500       DatatypeRepProofs.representation_proofs flat_names dt_info new_type_names descr sorts
   501         types_syntax constr_syntax;
   502 
   503     val (thy3, casedist_thms) =
   504       DatatypeAbsProofs.prove_casedist_thms new_type_names descr sorts induct thy2;
   505     val (thy4, reccomb_names, rec_thms) = DatatypeAbsProofs.prove_primrec_thms
   506       flat_names new_type_names descr sorts dt_info inject dist_rewrites dist_ss induct thy3;
   507     val (thy6, case_names, case_thms) = DatatypeAbsProofs.prove_case_thms
   508       flat_names new_type_names descr sorts reccomb_names rec_thms thy4;
   509     val (thy7, split_thms) = DatatypeAbsProofs.prove_split_thms new_type_names
   510       descr sorts inject dist_rewrites casedist_thms case_thms thy6;
   511     val (thy8, nchotomys) = DatatypeAbsProofs.prove_nchotomys new_type_names
   512       descr sorts casedist_thms thy7;
   513     val (thy9, case_congs) = DatatypeAbsProofs.prove_case_congs new_type_names
   514       descr sorts nchotomys case_thms thy8;
   515     val (thy10, size_thms) = DatatypeAbsProofs.prove_size_thms flat_names new_type_names
   516       descr sorts reccomb_names rec_thms thy9;
   517 
   518     val dt_infos = map (make_dt_info (flat descr) induct reccomb_names rec_thms)
   519       ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names ~~ case_thms ~~
   520         casedist_thms ~~ simproc_dists ~~ inject ~~ nchotomys ~~ case_congs);
   521 
   522     val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   523 
   524     val thy11 = thy10 |>
   525       Theory.add_path (space_implode "_" new_type_names) |>
   526       PureThy.add_thmss [(("simps", simps), [])] |>
   527       put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
   528       Theory.parent_path;
   529 
   530     val _ = store_clasimp thy11 ((claset_of thy11, simpset_of thy11)
   531       addsimps2 flat case_thms addsimps2 size_thms addsimps2 rec_thms
   532       addIffs flat (inject @ distinct));
   533 
   534   in
   535     (thy11,
   536      {distinct = distinct,
   537       inject = inject,
   538       exhaustion = casedist_thms,
   539       rec_thms = rec_thms,
   540       case_thms = case_thms,
   541       split_thms = split_thms,
   542       induction = induct,
   543       size = size_thms,
   544       simps = simps})
   545   end;
   546 
   547 
   548 (*********************** declare existing type as datatype *********************)
   549 
   550 fun gen_rep_datatype apply_theorems alt_names raw_distinct raw_inject raw_induction thy0 =
   551   let
   552     fun app_thmss srcs thy = foldl_map (fn (thy, x) => apply_theorems x thy) (thy, srcs);
   553     fun app_thm src thy = apsnd Library.hd (apply_theorems [src] thy);
   554 
   555     val (((thy1, induction), inject), distinct) = thy0
   556       |> app_thmss raw_distinct
   557       |> apfst (app_thmss raw_inject)
   558       |> apfst (apfst (app_thm raw_induction));
   559     val sign = Theory.sign_of thy1;
   560 
   561     val induction' = freezeT induction;
   562 
   563     fun err t = error ("Ill-formed predicate in induction rule: " ^
   564       Sign.string_of_term sign t);
   565 
   566     fun get_typ (t as _ $ Var (_, Type (tname, Ts))) =
   567           ((tname, map dest_TFree Ts) handle TERM _ => err t)
   568       | get_typ t = err t;
   569 
   570     val dtnames = map get_typ (dest_conj (HOLogic.dest_Trueprop (concl_of induction')));
   571     val new_type_names = if_none alt_names (map fst dtnames);
   572 
   573     fun get_constr t = (case Logic.strip_assums_concl t of
   574         _ $ (_ $ t') => (case head_of t' of
   575             Const (cname, cT) => (case strip_type cT of
   576                 (Ts, Type (tname, _)) => (tname, (cname, map (dtyp_of_typ dtnames) Ts))
   577               | _ => err t)
   578           | _ => err t)
   579       | _ => err t);
   580 
   581     fun make_dt_spec [] _ _ = []
   582       | make_dt_spec ((tname, tvs)::dtnames') i constrs =
   583           let val (constrs', constrs'') = take_prefix (equal tname o fst) constrs
   584           in (i, (tname, map DtTFree tvs, map snd constrs'))::
   585             (make_dt_spec dtnames' (i + 1) constrs'')
   586           end;
   587 
   588     val descr = make_dt_spec dtnames 0 (map get_constr (prems_of induction'));
   589     val sorts = add_term_tfrees (concl_of induction', []);
   590     val dt_info = get_datatypes thy1;
   591 
   592     val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
   593 
   594     val (thy2, casedist_thms) = thy1 |>
   595       DatatypeAbsProofs.prove_casedist_thms new_type_names [descr] sorts induction;
   596     val (thy3, reccomb_names, rec_thms) = DatatypeAbsProofs.prove_primrec_thms
   597       false new_type_names [descr] sorts dt_info inject distinct dist_ss induction thy2;
   598     val (thy4, case_names, case_thms) = DatatypeAbsProofs.prove_case_thms false
   599       new_type_names [descr] sorts reccomb_names rec_thms thy3;
   600     val (thy5, split_thms) = DatatypeAbsProofs.prove_split_thms
   601       new_type_names [descr] sorts inject distinct casedist_thms case_thms thy4;
   602     val (thy6, nchotomys) = DatatypeAbsProofs.prove_nchotomys new_type_names
   603       [descr] sorts casedist_thms thy5;
   604     val (thy7, case_congs) = DatatypeAbsProofs.prove_case_congs new_type_names
   605       [descr] sorts nchotomys case_thms thy6;
   606     val (thy8, size_thms) =
   607       if exists (equal "Arith") (Sign.stamp_names_of (Theory.sign_of thy7)) then
   608         DatatypeAbsProofs.prove_size_thms false new_type_names
   609           [descr] sorts reccomb_names rec_thms thy7
   610       else (thy7, []);
   611 
   612     val dt_infos = map (make_dt_info descr induction reccomb_names rec_thms)
   613       ((0 upto length descr - 1) ~~ descr ~~ case_names ~~ case_thms ~~
   614         casedist_thms ~~ map FewConstrs distinct ~~ inject ~~ nchotomys ~~ case_congs);
   615 
   616     val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   617 
   618     val thy9 = thy8 |>
   619       store_thmss "inject" new_type_names inject |>
   620       store_thmss "distinct" new_type_names distinct |>
   621       Theory.add_path (space_implode "_" new_type_names) |>
   622       PureThy.add_thms [(("induct", induction), [])] |>
   623       PureThy.add_thmss [(("simps", simps), [])] |>
   624       put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
   625       Theory.parent_path;
   626 
   627     val _ = store_clasimp thy9 ((claset_of thy9, simpset_of thy9)
   628       addsimps2 flat case_thms addsimps2 size_thms addsimps2 rec_thms
   629       addIffs flat (inject @ distinct));
   630 
   631   in
   632     (thy9,
   633      {distinct = distinct,
   634       inject = inject,
   635       exhaustion = casedist_thms,
   636       rec_thms = rec_thms,
   637       case_thms = case_thms,
   638       split_thms = split_thms,
   639       induction = induction,
   640       size = size_thms,
   641       simps = simps})
   642   end;
   643 
   644 val rep_datatype = gen_rep_datatype IsarThy.apply_theorems;
   645 val rep_datatype_i = gen_rep_datatype IsarThy.apply_theorems_i;
   646 
   647 
   648 (******************************** add datatype ********************************)
   649 
   650 fun gen_add_datatype prep_typ flat_names new_type_names dts thy =
   651   let
   652     val _ = Theory.requires thy "Datatype" "datatype definitions";
   653 
   654     (* this theory is used just for parsing *)
   655 
   656     val tmp_thy = thy |>
   657       Theory.copy |>
   658       Theory.add_types (map (fn (tvs, tname, mx, _) =>
   659         (tname, length tvs, mx)) dts);
   660 
   661     val sign = Theory.sign_of tmp_thy;
   662 
   663     val (tyvars, _, _, _)::_ = dts;
   664     val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
   665       let val full_tname = Sign.full_name sign (Syntax.type_name tname mx)
   666       in (case duplicates tvs of
   667             [] => if eq_set (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
   668                   else error ("Mutually recursive datatypes must have same type parameters")
   669           | dups => error ("Duplicate parameter(s) for datatype " ^ full_tname ^
   670               " : " ^ commas dups))
   671       end) dts);
   672 
   673     val _ = (case duplicates (map fst new_dts) @ duplicates new_type_names of
   674       [] => () | dups => error ("Duplicate datatypes: " ^ commas dups));
   675 
   676     fun prep_dt_spec ((dts', constr_syntax, sorts, i), (tvs, tname, mx, constrs)) =
   677       let
   678         fun prep_constr ((constrs, constr_syntax', sorts'), (cname, cargs, mx')) =
   679           let
   680             val (cargs', sorts'') = foldl (prep_typ sign) (([], sorts'), cargs);
   681             val _ = (case foldr add_typ_tfree_names (cargs', []) \\ tvs of
   682                 [] => ()
   683               | vs => error ("Extra type variables on rhs: " ^ commas vs))
   684           in (constrs @ [((if flat_names then Sign.full_name sign else
   685                 Sign.full_name_path sign tname) (Syntax.const_name cname mx'),
   686                    map (dtyp_of_typ new_dts) cargs')],
   687               constr_syntax' @ [(cname, mx')], sorts'')
   688           end handle ERROR =>
   689             error ("The error above occured in constructor " ^ cname ^
   690               " of datatype " ^ tname);
   691 
   692         val (constrs', constr_syntax', sorts') =
   693           foldl prep_constr (([], [], sorts), constrs)
   694 
   695       in 
   696         case duplicates (map fst constrs') of
   697            [] =>
   698              (dts' @ [(i, (Sign.full_name sign (Syntax.type_name tname mx),
   699                 map DtTFree tvs, constrs'))],
   700               constr_syntax @ [constr_syntax'], sorts', i + 1)
   701          | dups => error ("Duplicate constructors " ^ commas dups ^
   702              " in datatype " ^ tname)
   703       end;
   704 
   705     val (dts', constr_syntax, sorts', i) = foldl prep_dt_spec (([], [], [], 0), dts);
   706     val sorts = sorts' @ (map (rpair (Sign.defaultS sign)) (tyvars \\ map fst sorts'));
   707     val dt_info = get_datatypes thy;
   708     val (descr, _) = unfold_datatypes sign dts' sorts dt_info dts' i;
   709     val _ = check_nonempty descr;
   710 
   711   in
   712     (if (!quick_and_dirty) then add_datatype_axm else add_datatype_def)
   713       flat_names new_type_names descr sorts types_syntax constr_syntax dt_info thy
   714   end;
   715 
   716 val add_datatype_i = gen_add_datatype cert_typ;
   717 val add_datatype = gen_add_datatype read_typ;
   718 
   719 
   720 (** package setup **)
   721 
   722 (* setup theory *)
   723 
   724 val setup = [DatatypesData.init] @ simproc_setup;
   725 
   726 
   727 (* outer syntax *)
   728 
   729 local structure P = OuterParse and K = OuterSyntax.Keyword in
   730 
   731 val datatype_decl =
   732   Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.name -- P.opt_infix --
   733     (P.$$$ "=" |-- P.enum1 "|" (P.name -- Scan.repeat P.typ -- P.opt_mixfix --| P.marg_comment));
   734 
   735 fun mk_datatype args =
   736   let
   737     val names = map (fn ((((None, _), t), _), _) => t | ((((Some t, _), _), _), _) => t) args;
   738     val specs = map (fn ((((_, vs), t), mx), cons) => (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
   739   in #1 o add_datatype false names specs end;
   740 
   741 val datatypeP =
   742   OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
   743     (P.and_list1 datatype_decl >> (Toplevel.theory o mk_datatype));
   744 
   745 
   746 val rep_datatype_decl =
   747   Scan.option (Scan.repeat1 P.name) --
   748     Scan.optional (P.$$$ "distinct" |-- P.!!! (P.and_list1 P.xthms1)) [] --
   749     Scan.optional (P.$$$ "inject" |-- P.!!! (P.and_list1 P.xthms1)) [] --
   750     (P.$$$ "induction" |-- P.!!! P.xthm);
   751 
   752 fun mk_rep_datatype (((opt_ts, dss), iss), ind) = #1 o rep_datatype opt_ts dss iss ind;
   753 
   754 val rep_datatypeP =
   755   OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_decl
   756     (rep_datatype_decl >> (Toplevel.theory o mk_rep_datatype));
   757 
   758 
   759 val _ = OuterSyntax.add_keywords ["distinct", "inject", "induction"];
   760 val _ = OuterSyntax.add_parsers [datatypeP, rep_datatypeP];
   761 
   762 end;
   763 
   764 
   765 end;
   766 
   767 structure BasicDatatypePackage: BASIC_DATATYPE_PACKAGE = DatatypePackage;
   768 open BasicDatatypePackage;