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